The simplest correct approach is to compare every distinct pair of elements and check whether their absolute difference is strictly less than the threshold. For a list of length n, there are O(n²) pairs, which is fine for typical inputs. Edge cases: an empty list or a single element have no pairs and should return False; duplicate values have a difference of 0, which is less than any positive threshold and should return True.

```python
from typing import List

def has_close_elements(numbers: List[float], threshold: float) -> bool:
    n = len(numbers)
    for i in range(n):
        for j in range(i + 1, n):
            if abs(numbers[i] - numbers[j]) < threshold:
                return True
    return False
```


The function removes spaces and scans the string while tracking the nesting depth with a counter. A top-level group starts when the depth goes from 0 to 1 and ends when it returns to 0; characters are appended to a buffer during that span, and each completed group is added to the result.

```python
from typing import List

def separate_paren_groups(paren_string: str) -> List[str]:
    s = paren_string.replace(" ", "")
    result = []
    depth = 0
    start = 0
    buffer = []

    for i, ch in enumerate(s):
        if ch == '(':
            depth += 1
        elif ch == ')':
            depth -= 1

        buffer.append(ch)

        if depth == 0 and len(buffer) > 0:
            result.append("".join(buffer))
            buffer = []

    return result
```


The decimal part is the remainder after removing the integer part. For a positive number, the largest integer smaller than or equal to it is `math.floor(number)`, so the decimal part is `number - floor(number)`. This handles whole numbers (returns 0.0) and fractional values correctly.

```python
import math

def truncate_number(number: float) -> float:
    return number - math.floor(number)
```


The balance starts at zero and each operation is added to it. We iterate through the operations in order, updating the running balance and checking whether it ever becomes negative. If it does, we return True immediately; if we finish the list without the balance ever dropping below zero, we return False.

```python
from typing import List

def below_zero(operations: List[int]) -> bool:
    balance = 0
    for op in operations:
        balance += op
        if balance < 0:
            return True
    return False
```


The function first computes the arithmetic mean of the list, then sums the absolute differences between each element and that mean, and finally divides by the list length. Edge cases: an empty list would cause division by zero, so we return 0.0 (or could raise an error, but 0.0 is a common convention for empty datasets). Complexity is O(n) time and O(1) extra space.

```python
from typing import List

def mean_absolute_deviation(numbers: List[float]) -> float:
    if not numbers:
        return 0.0

    mean = sum(numbers) / len(numbers)
    return sum(abs(x - mean) for x in numbers) / len(numbers)
```


If the list is empty, there are no gaps to fill, so we return an empty list. For a non-empty list, we append the first element, then iterate through the remaining elements and append the delimiter before each one. This places exactly one delimiter between every consecutive pair.

```python
from typing import List

def intersperse(numbers: List[int], delimeter: int) -> List[int]:
    if not numbers:
        return []
    result = [numbers[0]]
    for num in numbers[1:]:
        result.append(delimeter)
        result.append(num)
    return result
```


For each space-separated group, we track the current nesting depth by incrementing on `(` and decrementing on `)`. The maximum value reached during that scan is the deepest nesting level for that group.

```python
from typing import List

def parse_nested_parens(paren_string: str) -> List[int]:
    results = []
    groups = paren_string.split()
    for group in groups:
        max_depth = 0
        current_depth = 0
        for char in group:
            if char == '(':
                current_depth += 1
                if current_depth > max_depth:
                    max_depth = current_depth
            elif char == ')':
                current_depth -= 1
        results.append(max_depth)
    return results
```


The function iterates through each string in the list and keeps only those where `substring` is present as a contiguous sequence (Python's `in` operator). An empty list returns an empty list, and an empty substring would match every string.

```python
from typing import List

def filter_by_substring(strings: List[str], substring: str) -> List[str]:
    return [s for s in strings if substring in s]
```


The function initializes `total_sum` to 0 and `total_product` to 1, then iterates through the list once, adding each number to the sum and multiplying the product by it. An empty list naturally returns (0, 1) because the loop never runs. Time complexity is O(n) and space is O(1).

```python
from typing import List, Tuple

def sum_product(numbers: List[int]) -> Tuple[int, int]:
    total_sum = 0
    total_product = 1
    for num in numbers:
        total_sum += num
        total_product *= num
    return total_sum, total_product
```


The rolling maximum at each index is the maximum of all elements seen so far. We can maintain a running maximum as we iterate through the list once, updating it whenever we see a larger value and appending the current maximum to the result. This is O(n) time and O(n) space for the output list.

```python
from typing import List

def rolling_max(numbers: List[int]) -> List[int]:
    if not numbers:
        return []

    result = []
    current_max = numbers[0]

    for num in numbers:
        if num > current_max:
            current_max = num
        result.append(current_max)

    return result
```


The shortest palindrome starting with `string` is formed by keeping the longest palindromic suffix intact and appending the reverse of whatever prefix precedes it. For example, in `"cata"`, the longest palindromic suffix is `"ata"`, so we append the reverse of `"c"`, yielding `"catac"`. We scan from the longest possible suffix down to the last character and stop at the first palindrome found.

```python
def is_palindrome(string: str) -> bool:
    """ Test if given string is a palindrome """
    return string == string[::-1]

def make_palindrome(string: str) -> str:
    """ Find the shortest palindrome that begins with a supplied string. """
    if not string:
        return ""

    for i in range(len(string)):
        suffix = string[i:]
        if is_palindrome(suffix):
            prefix = string[:i]
            return string + prefix[::-1]
```


The function compares each character pair at the same index and appends `'1'` when they differ and `'0'` when they are the same, which is the definition of XOR for binary digits. The result is built as a list and joined at the end for O(n) time and space.

```python
def string_xor(a: str, b: str) -> str:
    return ''.join('1' if c1 != c2 else '0' for c1, c2 in zip(a, b))
```


The function handles the empty list by returning `None` immediately. For a non-empty list, it uses Python's `max` with `len` as the key; because `max` is stable and returns the first occurrence when keys tie, this naturally satisfies the requirement to return the first longest string.

```python
from typing import List, Optional

def longest(strings: List[str]) -> Optional[str]:
    if not strings:
        return None
    return max(strings, key=len)
```


The Euclidean algorithm repeatedly replaces the larger number with the remainder of the division until one number becomes zero; the non-zero value remaining is the greatest common divisor. This handles any pair of integers, including cases where one input is already a divisor of the other.

```python
def greatest_common_divisor(a: int, b: int) -> int:
    """ Return a greatest common divisor of two integers a and b
    >>> greatest_common_divisor(3, 5)
    1
    >>> greatest_common_divisor(25, 15)
    5
    """
    a, b = abs(a), abs(b)
    while b:
        a, b = b, a % b
    return a
```


Each prefix is a substring from index 0 to some end index `i` (where `i` ranges from 1 to the length of the string). Slicing `string[:i]` naturally produces prefixes in increasing order of length, so we can build the list with a single loop. An empty string yields an empty list because the range is empty.

```python
from typing import List

def all_prefixes(string: str) -> List[str]:
    return [string[:i] for i in range(1, len(string) + 1)]
```


The function generates a range from 0 to n inclusive, converts each integer to a string, and joins them with a single space. For n=0, the range has one element ('0'); for larger n, it produces the full sequence. Time and space complexity are both O(n).

```python
def string_sequence(n: int) -> str:
    return ' '.join(str(i) for i in range(n + 1))
```


To count distinct characters regardless of case, normalize the entire string to lowercase and add each character to a set; duplicates are automatically collapsed, and the set's length is the answer.

```python
def count_distinct_characters(string: str) -> int:
    return len(set(string.lower()))
```


The function splits the string on whitespace and maps each token to its beat value: `'o'` → 4, `'o|'` → 2, and `'.|'` → 1. This matches the legend exactly and handles any number of notes in a single pass.

```python
from typing import List

def parse_music(music_string: str) -> List[int]:
    mapping = {
        'o': 4,
        'o|': 2,
        '.|': 1,
    }
    return [mapping[note] for note in music_string.split()]
```


ossible starting index in `string` and check whether `substring` matches the slice at that position. This correctly identifies all overlapping cases (e.g. `'aa'` in `'aaaa'` at indices 0, 1, and 2).
       ^^^^^
SyntaxError: invalid syntax

To count overlapping occurrences, we cannot use `str.count`, which only counts non-overlapping matches. Instead, we iterate through every possible starting index in `string` and check whether `substring` matches the slice at that position. This correctly identifies all overlapping cases (e.g. `'aa'` in `'aaaa'` at indices 0, 1, and 2).

Edge cases:
- If `substring` is empty, the loop would match at every index; the problem examples imply non-empty substrings, but we can guard with `if not substring: return 0`.
- If `string` is shorter than `substring`, the loop never executes and returns 0.
- If `string` is empty, it returns 0.

Complexity: O(n * m) where n is len(string) and m is len(substring).


Map each word to its integer value, sort the words by those values, and join them back into a space-delimited string.

```python
from typing import List

def sort_numbers(numbers: str) -> str:
    mapping = {
        'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4,
        'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9
    }
    words = numbers.split()
    sorted_words = sorted(words, key=lambda w: mapping[w])
    return ' '.join(sorted_words)
```


Sort the list so that adjacent elements are the closest candidates. Iterate through the sorted list once, tracking the pair with the minimum absolute difference, and return that pair as a tuple in ascending order.

```python
from typing import List, Tuple

def find_closest_elements(numbers: List[float]) -> Tuple[float, float]:
    sorted_nums = sorted(numbers)
    min_diff = float('inf')
    closest_pair = (sorted_nums[0], sorted_nums[1])

    for i in range(len(sorted_nums) - 1):
        diff = sorted_nums[i + 1] - sorted_nums[i]
        if diff < min_diff:
            min_diff = diff
            closest_pair = (sorted_nums[i], sorted_nums[i + 1])

    return closest_pair
```


The transformation is a standard min-max normalization: for each value `x`, the new value is `(x - min) / (max - min)`. The smallest value maps to 0, the largest to 1, and intermediate values are linearly interpolated between them. If all numbers are equal, the denominator is zero; the problem guarantees at least two elements and the example implies distinct values, but a guard for `max == min` would return a list of zeros.

```python
from typing import List

def rescale_to_unit(numbers: List[float]) -> List[float]:
    min_val = min(numbers)
    max_val = max(numbers)
    range_val = max_val - min_val

    if range_val == 0:
        return [0.0] * len(numbers)

    return [(x - min_val) / range_val for x in numbers]
```


Use `isinstance(value, int)` to keep only integer types; this correctly excludes strings, floats, lists, dicts, and booleans (since `bool` is a subclass of `int` in Python, `isinstance(True, int)` is true—if booleans must be excluded, add `and not isinstance(value, bool)`). The list comprehension builds the result in O(n) time.

```python
from typing import List, Any

def filter_integers(values: List[Any]) -> List[int]:
    return [value for value in values if isinstance(value, int) and not isinstance(value, bool)]
```


The function can be implemented by calling Python's built-in `len()` on the input string, which returns the number of characters in O(1) time for Python strings. This correctly handles the empty string (0) and any other valid Python string.

```python
def strlen(string: str) -> int:
    """ Return length of given string
    >>> strlen('')
    0
    >>> strlen('abc')
    3
    """
    return len(string)
```


The largest proper divisor of `n` is `n` divided by its smallest prime factor. We scan from 2 up to `sqrt(n)`; the first divisor found is the smallest prime factor, so `n // i` is the largest proper divisor. If no divisor is found, `n` is prime and the answer is 1.

```python
import math

def largest_divisor(n: int) -> int:
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return n // i
    return 1
```


Trial division from 2 upwards: repeatedly divide by the smallest possible factor until n is 1. Each successful division appends that factor; the remaining n after the loop is the last prime factor (if any). Factors are naturally collected smallest to largest.

```python
from typing import List

def factorize(n: int) -> List[int]:
    factors = []
    d = 2
    while d * d <= n:
        while n % d == 0:
            factors.append(d)
            n //= d
        d += 1
    if n > 1:
        factors.append(n)
    return factors
```


Count each number first, then build the result by including only those with a count of 1 while preserving the original order. This is O(n) time and O(n) space.

```python
from typing import List
from collections import Counter

def remove_duplicates(numbers: List[int]) -> List[int]:
    counts = Counter(numbers)
    return [num for num in numbers if counts[num] == 1]
```


Each character is processed independently: `isupper()` and `islower()` identify the case, and `upper()` / `lower()` perform the flip. Non-alphabetic characters remain unchanged because neither check applies. Joining the list of transformed characters yields the final string in O(n) time.

```python
def flip_case(string: str) -> str:
    result = []
    for char in string:
        if char.isupper():
            result.append(char.lower())
        elif char.islower():
            result.append(char.upper())
        else:
            result.append(char)
    return ''.join(result)
```


The simplest and most efficient approach in Python is to join the list with an empty separator, which handles the empty list case naturally and concatenates all elements in order.

```python
from typing import List

def concatenate(strings: List[str]) -> str:
    """ Concatenate list of strings into a single string
    >>> concatenate([])
    ''
    >>> concatenate(['a', 'b', 'c'])
    'abc'
    """
    return ''.join(strings)
```


The function iterates through each string and uses `startswith(prefix)` to keep only those that begin with the specified prefix. Empty lists return an empty list, and strings shorter than the prefix are correctly excluded.

```python
from typing import List

def filter_by_prefix(strings: List[str], prefix: str) -> List[str]:
    return [s for s in strings if s.startswith(prefix)]
```


A positive number is strictly greater than zero, so we filter the list with `x > 0` and build a new list in order. This handles empty lists, all-negative lists, and duplicates correctly.

```python
def get_positive(l):
    return [x for x in l if x > 0]
```


Numbers less than 2 are not prime. For n ≥ 2, we check divisibility by 2 and 3 first, then test odd divisors from 5 up to √n in steps of 6 (testing i and i+2), which skips multiples of 2 and 3. This trial division has O(√n) time complexity.

```python
def is_prime(n):
    if n < 2:
        return False
    if n in (2, 3):
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True
```


The problem guarantees a solution when the coefficient list has an even length and the largest coefficient is non-zero. For a linear polynomial `[a, b]`, the zero is `-a/b`. For higher-degree polynomials, the examples suggest returning the smallest positive real root (1.0 for the cubic). A robust approach is to sample the function over a reasonable range and use a bisection search on the first interval where the sign flips.

```python
import math

def poly(xs, x):
    return sum(coeff * math.pow(x, i) for i, coeff in enumerate(xs))

def find_zero(xs):
    def evaluate(x):
        return poly(xs, x)

    # Sample the function to find a sign change
    samples = list(range(-100, 101))
    for i in range(len(samples) - 1):
        a, b = samples[i], samples[i + 1]
        if evaluate(a) * evaluate(b) <= 0:
            # Bisection method
            low, high = a, b
            for _ in range(50):
                mid = (low + high) / 2
                if evaluate(low) * evaluate(mid) <= 0:
                    high = mid
                else:
                    low = mid
            return mid
    return 0.0
```


The function identifies all values at indices divisible by three (0, 3, 6, ...), sorts them, and places them back into those same positions while leaving all other elements unchanged. The doctest examples confirm this: in `[5, 6, 3, 4, 8, 9, 2]`, indices 0, 3, and 6 hold `5`, `4`, and `2`; sorted they become `2`, `4`, `5`, so the result is `[2, 6, 3, 4, 8, 9, 5]`.

```python
def sort_third(l):
    values = [l[i] for i in range(len(l)) if i % 3 == 0]
    values.sort()
    result = l[:]
    values_iter = iter(values)
    for i in range(len(l)):
        if i % 3 == 0:
            result[i] = next(values_iter)
    return result
```


The simplest approach is to convert the list to a set to remove duplicates, then sort the result. Sets automatically handle repeated values, and `sorted()` returns a new list in ascending order.

```python
def unique(l):
    return sorted(set(l))
```


The function can be implemented with Python's built-in `max()`, which returns the largest value in an iterable. For an empty list, `max()` would raise a ValueError, which is the standard behavior for this operation in Python.

```python
def max_element(l):
    return max(l)
```


Iterate through each integer from 0 up to `n-1`. For each number, check if it is divisible by 11 or 13; if so, convert the number to a string and count how many times the character '7' appears. Sum these counts. Edge cases: if `n <= 0`, the loop never runs and the result is 0; numbers like 77 are counted because they are divisible by 11 and contain two 7s.

```python
def fizz_buzz(n):
    count = 0
    for i in range(n):
        if i % 11 == 0 or i % 13 == 0:
            count += str(i).count('7')
    return count
```


The function extracts all values at even indices (0, 2, 4, ...), sorts them, and then reconstructs the list by placing the sorted values back into those same positions while keeping the odd-indexed values unchanged. This matches the doctest examples: `[5, 6, 3, 4]` has even-indexed values `[5, 3]`, which sort to `[3, 5]`, yielding `[3, 6, 5, 4]`.

```python
def sort_even(l):
    even_values = sorted(l[::2])
    result = l[:]
    result[::2] = even_values
    return result
```


e "/var/folders/0l/75d7q65918d_j14rb3j30dlm0000gn/T/tmp3p_5_zrg/cand.py", line 30, in check
    encoded_str = encode_cyclic(str)
                  ^^^^^^^^^^^^^
NameError: name 'encode_cyclic' is not defined. Did you mean: 'decode_cyclic'?

The encoding rule is a left cyclic shift on groups of exactly three characters: `(group[1:] + group[0])` for length-3 groups, and no change for shorter trailing groups. Decoding is the inverse: for each length-3 group, the last character moves to the front (`group[-1] + group[:-1]`), and shorter groups are left unchanged.

```python
def decode_cyclic(s):
    groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)]
    groups = [(group[-1] + group[:-1]) if len(group) == 3 else group for group in groups]
    return "".join(groups)
```


We generate Fibonacci numbers iteratively and test each for primality until we find the n-th one. Primality is checked with trial division up to √F; numbers less than 2 are skipped. Complexity is dominated by the growth of Fibonacci numbers and the primality tests.

```python
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

def prime_fib(n):
    count = 0
    a, b = 0, 1
    while count < n:
        a, b = b, a + b
        if is_prime(a):
            count += 1
            if count == n:
                return a
```


The function checks every combination of three distinct indices using three nested loops and returns `True` as soon as it finds a triple whose values sum to zero. This correctly handles duplicates (e.g. `[1, 3, -2, 1]` uses the two `1`s at different positions) and returns `False` if no such triple exists or if the list has fewer than three elements.

```python
def triples_sum_to_zero(l):
    n = len(l)
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                if l[i] + l[j] + l[k] == 0:
                    return True
    return False
```


Each car in the left-to-right set will eventually pass every car in the right-to-left set because they move in opposite directions at the same speed and the road is infinitely long. A collision occurs exactly when a left-to-right car and a right-to-left car meet; since every pair of cars from opposite sets must cross paths once and only once, the total number of collisions is the product of the number of cars in each set.

```python
def car_race_collision(n):
    return n * n
```


The function can be implemented with a list comprehension that iterates over each element and adds 1. This creates a new list without modifying the input, which is the standard expected behavior for this kind of operation.

```python
def incr_list(l):
    return [x + 1 for x in l]
```


We need to find two distinct elements whose sum is zero, which is equivalent to finding a pair `(x, -x)` where the two elements are at different indices. A single `0` does not count because we need two distinct elements. We can track seen values in a set and, for each number, check if its negation is already in the set. If `x == 0`, we only count it if we have already seen another `0`.

```python
def pairs_sum_to_zero(l):
    seen = set()
    for num in l:
        target = -num
        if target in seen:
            return True
        seen.add(num)
    return False
```


Since the base is always less than 10, each digit is a single decimal character and no letter mapping is needed. The algorithm repeatedly takes `x % base` as the current digit and sets `x //= base`, prepending each digit to a list and reversing at the end. Edge case: `x == 0` should return `'0'` rather than an empty string.

```python
def change_base(x, base):
    if x == 0:
        return '0'
    digits = []
    while x > 0:
        digits.append(str(x % base))
        x //= base
    return ''.join(reversed(digits))
```


The area of a triangle is half the base times the height. The function takes the side length `a` as the base and `h` as the height, then returns `0.5 * a * h`.

```python
def triangle_area(a, h):
    """Given length of a side and high return area for a triangle.
    >>> triangle_area(5, 3)
    7.5
    """
    return 0.5 * a * h
```


The sequence is defined by four base cases and a four-term recurrence. An iterative approach with a sliding window of the last four values computes each term in O(n) time and O(1) space, avoiding the exponential cost of naive recursion.

```python
def fib4(n):
    if n == 0 or n == 1 or n == 3:
        return 0
    if n == 2:
        return 2

    a, b, c, d = 0, 0, 2, 0
    for _ in range(n - 3):
        next_val = a + b + c + d
        a, b, c, d = b, c, d, next_val

    return d
```


The median is the middle value of a sorted list. For an odd number of elements, it is the element at index `n // 2`; for an even number, it is the average of the two middle elements. Sorting takes O(n log n) time and O(n) extra space in Python's Timsort.

```python
def median(l):
    sorted_l = sorted(l)
    n = len(sorted_l)
    if n == 0:
        return None
    mid = n // 2
    if n % 2 == 1:
        return sorted_l[mid]
    else:
        return (sorted_l[mid - 1] + sorted_l[mid]) / 2.0
```


A palindrome reads the same forward and backward, so the simplest check is to compare the string to its reverse. An empty string is a palindrome by definition (it equals its reverse), and single-character strings also pass. This approach is O(n) time and O(n) space for the reversed copy.

```python
def is_palindrome(text):
    return text == text[::-1]
```


The function computes 2^n modulo p using modular exponentiation. Python's built-in `pow(base, exp, mod)` implements the binary exponentiation algorithm (square-and-multiply), which keeps intermediate results bounded by p and runs in O(log n) time, avoiding the overflow that would occur if we computed 2^n directly.

```python
def modp(n, p):
    return pow(2, n, p)
```


 File "/var/folders/0l/75d7q65918d_j14rb3j30dlm0000gn/T/tmpez3lhbjw/cand.py", line 29, in check
    encoded_str = encode_shift(str)
                  ^^^^^^^^^^^^
NameError: name 'encode_shift' is not defined. Did you mean: 'decode_shift'?

The decoding is the inverse of the encoding: instead of adding 5, subtract 5. The formula `(ord(ch) - ord("a") - 5) % 26` handles the wrap-around correctly because Python's modulo operator returns a positive result for negative numbers (e.g. -1 % 26 = 25).

```python
def decode_shift(s):
    return "".join([chr(((ord(ch) - ord("a") - 5) % 26) + ord("a")) for ch in s])
```


The function iterates through each character and keeps only those that are not in the set of vowels (both lowercase and uppercase). This handles empty strings, strings with only vowels, mixed case, and newline characters correctly.

```python
def remove_vowels(text):
    vowels = set("aeiouAEIOU")
    return "".join(char for char in text if char not in vowels)
```


The function checks whether every element in `l` is strictly less than `t`. An empty list vacuously satisfies the condition (all zero elements are below the threshold), so it returns `True`. The approach uses Python's `all()` with a generator expression for short-circuiting: as soon as one element is found that is greater than or equal to `t`, the function returns `False`.

```python
def below_threshold(l, t):
    return all(x < t for x in l)
```


The function simply returns the sum of the two integer arguments using Python's `+` operator, which handles positive, negative, and zero values correctly.

```python
def add(x: int, y: int):
    """Add two numbers x and y
    >>> add(2, 3)
    5
    >>> add(5, 7)
    12
    """
    return x + y
```


The problem asks whether two strings contain the same set of distinct characters, regardless of frequency or order. The simplest approach is to compare the sets of each string: `set(s0) == set(s1)` is true if and only if every character that appears in `s0` also appears in `s1` and vice versa.

Edge cases: empty strings both yield empty sets (True); strings with different lengths but the same character set (e.g. `'abcd'` vs `'dddddddabc'`) are True; any extra character in either string makes the sets unequal (False).

```python
def same_chars(s0, s1):
    return set(s0) == set(s1)
```


The function uses an iterative approach with two variables to track the last two Fibonacci numbers, which is O(n) time and O(1) space. The base cases are handled by returning 0 for n=0 and 1 for n=1, and the loop builds up to the n-th value.

```python
def fib(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    a, b = 0, 1
    for _ in range(2, n + 1):
        a, b = b, a + b
    return b
```


Use a counter to track nesting depth: increment on `<` and decrement on `>`. If the counter ever goes negative, a closing bracket appeared without a matching opener. At the end, the counter must be exactly zero so every opener was closed.

```python
def correct_bracketing(brackets):
    depth = 0
    for char in brackets:
        if char == '<':
            depth += 1
        elif char == '>':
            depth -= 1
            if depth < 0:
                return False
    return depth == 0
```


A list is monotonic if every adjacent pair is non-decreasing or every adjacent pair is non-increasing. We can check both directions with `all()` over pairs; if either holds, the list is monotonic. Empty lists and single-element lists vacuously satisfy both directions and return True.

```python
def monotonic(l):
    increasing = all(l[i] <= l[i + 1] for i in range(len(l) - 1))
    decreasing = all(l[i] >= l[i + 1] for i in range(len(l) - 1))
    return increasing or decreasing
```


The simplest approach is to convert both lists to sets and take their intersection, which automatically removes duplicates and keeps only elements present in both lists. Sorting the result gives the required order. Time complexity is O(n + m + k log k) where n and m are the list lengths and k is the number of common elements.

```python
def common(l1, l2):
    return sorted(set(l1) & set(l2))
```


Trial division from the smallest prime upwards: repeatedly divide out each factor until `n` is fully factored; the last factor remaining is the largest prime factor. Complexity is O(√n) worst case.

```python
def largest_prime_factor(n):
    factor = 2
    while factor * factor <= n:
        if n % factor == 0:
            n //= factor
        else:
            factor += 1
    return n
```


The sum of all integers from 1 to n can be computed in O(1) time using the arithmetic series formula: n * (n + 1) / 2. For n = 1, it correctly yields 1; for larger n, it matches the doctest examples (e.g., 30 → 465, 100 → 5050).

```python
def sum_to_n(n):
    return n * (n + 1) // 2
```


Use a counter to track nesting depth: increment on `(` and decrement on `)`. If the counter ever goes negative, a closing bracket appeared without a matching opener. At the end, the counter must be exactly zero so every opener was closed.

```python
def correct_bracketing(brackets):
    balance = 0
    for char in brackets:
        if char == '(':
            balance += 1
        elif char == ')':
            balance -= 1
            if balance < 0:
                return False
    return balance == 0
```


For each term `xs[i] * x^i`, the derivative is `i * xs[i] * x^(i-1)`. The constant term `xs[0]` disappears, so we skip it and build the new coefficient list by multiplying each remaining coefficient by its original index. An empty list or a single constant returns an empty list.

```python
def derivative(xs):
    return [i * coeff for i, coeff in enumerate(xs[1:], 1)]
```


The sequence is a 3-term recurrence with base cases fibfib(0)=0, fibfib(1)=0, and fibfib(2)=1. For n >= 3, each term is the sum of the previous three. Iterative DP with three variables computes the n-th term in O(n) time and O(1) space, avoiding the exponential cost of naive recursion.

```python
def fibfib(n):
    if n == 0 or n == 1:
        return 0
    if n == 2:
        return 1
    a, b, c = 0, 0, 1
    for _ in range(3, n + 1):
        a, b, c = b, c, a + b + c
    return c
```


The function iterates through each character and checks against the standard vowels `aeiou` (case-insensitive). For the special rule on `y`, it only counts `y` when the character is at the last index of the string. This matches both examples: `"abcde"` has 2 standard vowels; `"ACEDY"` has 2 standard vowels plus the trailing `y`, totaling 3.

```python
def vowels_count(s):
    vowels = set("aeiouAEIOU")
    count = 0
    for i, char in enumerate(s):
        if char in vowels:
            count += 1
        elif char.lower() == 'y' and i == len(s) - 1:
            count += 1
    return count
```


The function converts the integer to a string to treat each digit as a unit. For a right circular shift, the last `shift` digits move to the front and the rest follow. If `shift` equals the number of digits, the entire string is rotated back to its original order. The special case `shift > len(digits)` returns the digits reversed, as specified.

```python
def circular_shift(x, shift):
    digits = str(x)
    n = len(digits)
    if shift > n:
        return digits[::-1]
    if shift == n:
        return digits
    return digits[-shift:] + digits[:-shift]
```


The function iterates through each character in the string and adds its ASCII value (via `ord()`) to a running total only when `char.isupper()` is true. An empty string naturally yields 0. Time complexity is O(n) and space is O(1).

```python
def digitSum(s):
    total = 0
    for char in s:
        if char.isupper():
            total += ord(char)
    return total
```


The function parses the two numbers from the string by splitting on whitespace and converting the first and third tokens to integers (the second token is the word "apples" or "oranges"). The number of mangoes is then the total `n` minus the sum of those two values.

```python
def fruit_distribution(s, n):
    parts = s.split()
    apples = int(parts[0])
    oranges = int(parts[3])
    return n - apples - oranges
```


We iterate through the array once while tracking the best candidate found so far. For each even value, we update the candidate only when we see a value strictly smaller than the current best; this naturally preserves the smallest index when values are equal. If no even value is encountered, we return an empty list.

```python
def pluck(arr):
    best_value = float('inf')
    best_index = -1

    for i, value in enumerate(arr):
        if value % 2 == 0:
            if value < best_value:
                best_value = value
                best_index = i

    if best_index == -1:
        return []

    return [best_value, best_index]
```


Count each integer's frequency, filter for values where `frequency >= value`, and return the maximum of those values or -1 if the filtered list is empty.

```python
from collections import Counter

def search(lst):
    counts = Counter(lst)
    candidates = [val for val, freq in counts.items() if freq >= val]
    return max(candidates) if candidates else -1
```


The approach is to sort the list first so that the minimum and maximum are always at the ends. We then use two pointers (left and right) and alternate between taking the left element (minimum) and the right element (maximum) until the pointers meet. Duplicates are handled naturally because each index is consumed exactly once.

```python
def strange_sort_list(lst):
    if not lst:
        return []

    sorted_lst = sorted(lst)
    result = []
    left, right = 0, len(sorted_lst) - 1
    turn = 0

    while left <= right:
        if turn % 2 == 0:
            result.append(sorted_lst[left])
            left += 1
        else:
            result.append(sorted_lst[right])
            right -= 1
        turn += 1

    return result
```


Use Heron's formula: first validate the triangle with the triangle inequality (each pair's sum must exceed the third side), then compute the semi-perimeter `s`, the area as `sqrt(s * (s-a) * (s-b) * (s-c))`, and round to 2 decimal places.

```python
import math

def triangle_area(a, b, c):
    if a + b > c and a + c > b and b + c > a:
        s = (a + b + c) / 2
        area = math.sqrt(s * (s - a) * (s - b) * (s - c))
        return round(area, 2)
    return -1
```


The function checks two conditions: whether the list `q` is a palindrome (`q == q[::-1]`) and whether the sum of its elements is at most `w`. Both must be true for the object to fly.

```python
def will_it_fly(q, w):
    is_balanced = q == q[::-1]
    is_light_enough = sum(q) <= w
    return is_balanced and is_light_enough
```


To make the array a palindrome, each pair of symmetric indices `(i, n - 1 - i)` must have equal values. For each pair where the values differ, exactly one change is needed (set one element to match the other). Pairs that already match require no change. The total minimum changes is the count of mismatched symmetric pairs.

```python
def smallest_change(arr):
    n = len(arr)
    changes = 0
    for i in range(n // 2):
        if arr[i] != arr[n - 1 - i]:
            changes += 1
    return changes
```


Calculate the sum of lengths of all strings in each list. Compare the two totals: return the list with the smaller total, or the first list if they are equal. Empty lists naturally sum to 0 and are handled correctly.

```python
def total_match(lst1, lst2):
    total1 = sum(len(s) for s in lst1)
    total2 = sum(len(s) for s in lst2)

    if total1 <= total2:
        return lst1
    return lst2
```


Since `a` is less than 100, we can factorize it completely and count how many prime factors it has (counting multiplicity). A number is the product of exactly 3 primes if and only if it has exactly 3 prime factors. For example, 30 = 2 × 3 × 5 (3 factors), while 12 = 2 × 2 × 3 (3 factors) and 8 = 2 × 2 × 2 (3 factors).

```python
def is_multiply_prime(a):
    count = 0
    d = 2
    temp = a
    while d * d <= temp:
        while temp % d == 0:
            count += 1
            temp //= d
        d += 1
    if temp > 1:
        count += 1
    return count == 3
```


Edge cases: `x=1` is always true for any `n` (exponent 0); `n=1` is only true when `x=1`; `n=0` is only true when `x=0` (exponent 1) or `x=1` (exponent 0); negative `x` with even `n` is impossible; negative `n` with odd exponents can work but the problem examples imply positive bases. The approach: if `x==1` return True; if `n==0` return `x==0`; if `n==1` return `x==1`; otherwise repeatedly multiply by `n` while the product is less than `x`, then check equality.

```python
def is_simple_power(x, n):
    if x == 1:
        return True
    if n == 0:
        return x == 0
    if n == 1:
        return x == 1

    product = n
    while product < x:
        product *= n

    return product == x
```


For a valid integer `a`, we can check if it is a perfect cube by taking the integer cube root (using `round(a**(1/3))` for positive values and `round(-(-a)**(1/3))` for negative values) and verifying that cubing that root equals `a`. This handles positive, negative, and zero correctly.

```python
def iscube(a):
    if a >= 0:
        root = round(a**(1/3))
    else:
        root = round(-(-a)**(1/3))
    return root**3 == a
```


The prime hexadecimal digits are 2, 3, 5, 7 (decimal), B (11), and D (13). We can map each uppercase hex character to its decimal value and count how many fall into that set.

```python
def hex_key(num):
    primes = {2, 3, 5, 7, 11, 13}
    hex_map = {
        '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,
        '8': 8, '9': 9, 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15
    }
    count = 0
    for char in num:
        if hex_map[char] in primes:
            count += 1
    return count
```


The function converts the decimal integer to a binary string using Python's built-in `bin()` (which returns a string prefixed with `0b`), strips that prefix, and wraps the result in the required `db` markers. Edge cases like `0` correctly yield `db0db`.

```python
def decimal_to_binary(decimal):
    binary = bin(decimal)[2:]
    return f"db{binary}db"
```


The function first checks the minimum length requirement (at least 3). Then it slides a window of size 3 across the string and verifies that each window contains three distinct characters using a set. If any window has duplicates, the string is not happy.

```python
def is_happy(s):
    if len(s) < 3:
        return False
    for i in range(len(s) - 2):
        window = s[i:i+3]
        if len(set(window)) != 3:
            return False
    return True
```


The grading table is a chain of strict inequalities (`>`) with a special case for exactly `4.0` and exactly `0.0`. The correct order is to check the highest threshold first and fall through; for each grade, we compare against the thresholds in descending order and return the first grade that satisfies the condition. The `4.0` and `0.0` cases are handled as the first and last checks respectively.

```python
def numerical_letter_grade(grades):
    letter_grades = []
    for gpa in grades:
        if gpa == 4.0:
            letter_grades.append("A+")
        elif gpa > 3.7:
            letter_grades.append("A")
        elif gpa > 3.3:
            letter_grades.append("A-")
        elif gpa > 3.0:
            letter_grades.append("B+")
        elif gpa > 2.7:
            letter_grades.append("B")
        elif gpa > 2.3:
            letter_grades.append("B-")
        elif gpa > 2.0:
            letter_grades.append("C+")
        elif gpa > 1.7:
            letter_grades.append("C")
        elif gpa > 1.3:
            letter_grades.append("C-")
        elif gpa > 1.0:
            letter_grades.append("D+")
        elif gpa > 0.7:
            letter_grades.append("D")
        elif gpa > 0.0:
            letter_grades.append("D-")
        else:
            letter_grades.append("E")
    return letter_grades
```


The function first computes the length of the input string. A length of 0 or 1 is not prime, so those cases return False immediately. For lengths 2 and 3, the function returns True. For any length greater than 3, it checks divisibility by 2 and 3, then iterates through odd numbers starting from 5 and skipping multiples of 2 and 3 (the 6k ± 1 rule), which is a standard primality test with O(√n) complexity.

```python
def prime_length(string):
    n = len(string)
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True
```


, in <module>
    check(starts_one_ends)
    ~~~~~^^^^^^^^^^^^^^^^^
  File "/var/folders/0l/75d7q65918d_j14rb3j30dlm0000gn/T/tmpm2k9_k04/cand.py", line 26, in check
    assert candidate(2) == 18
           ^^^^^^^^^^^^^^^^^^
AssertionError

We can use the principle of inclusion-exclusion on the set of n-digit positive integers. There are $9 \cdot 10^{n-1}$ such numbers. The numbers starting with 1 are those of the form $1 \dots$, which has $10^{n-1}$ values. The numbers ending with 1 are those of the form $\dots 1$, which also has $9 \cdot 10^{n-2}$ values (the first digit cannot be 0). The intersection is the set of numbers starting and ending with 1, which has $9 \cdot 10^{n-2}$ values for $n \ge 2$ (first digit 1–9, last digit fixed to 1, middle $n-2$ digits free). For $n=1$, the only such number is 1, so the answer is 1.

```python
def starts_one_ends(n):
    if n == 1:
        return 1
    starts = 10**(n - 1)
    ends = 9 * 10**(n - 2)
    both = 9 * 10**(n - 2)
    return starts + ends - both
```


 <module>
    check(solve)
    ~~~~~^^^^^^^
  File "/var/folders/0l/75d7q65918d_j14rb3j30dlm0000gn/T/tmpilveykt2/cand.py", line 20, in check
    assert candidate(1000) == "1", "Error"
           ^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Error

The problem asks for the binary representation of `N` as a string, not the sum of its digits (the examples clarify this: 1000 → "1", 150 → "110", 147 → "1100"). Python's `bin(N)` returns a string prefixed with `0b`, so we slice from index 2. For `N=0`, `bin(0)` is `0b0`, which correctly yields `"0"`.

```python
def solve(N):
    return bin(N)[2:]
```


The function iterates over the list with `enumerate` to track each element's index. It selects elements where the index is odd (1, 3, 5, ...) and adds them to the total only if the value itself is even. This matches the example: in `[4, 2, 6, 7]`, index 1 is `2` (even → add) and index 3 is `7` (odd → skip), so the result is `2`.

```python
def add(lst):
    total = 0
    for i, num in enumerate(lst):
        if i % 2 == 1 and num % 2 == 0:
            total += num
    return total
```


The function splits the input into words and spaces while preserving the original sequence. For each word, it sorts the characters by ASCII value and joins them; spaces are left unchanged. This matches the examples: 'Hi' stays 'Hi' (already sorted), 'hello' becomes 'ehllo', and 'Hello World!!!' becomes 'Hello !!!Wdlor' (the word 'World!!!' is treated as one token and sorted).

```python
def anti_shuffle(s):
    words = s.split(' ')
    result = []
    for word in words:
        if word == '':
            result.append('')
        else:
            result.append(''.join(sorted(word)))
    return ' '.join(result)
```


The function iterates through each row with index `r` and each element with column index `c`. When an element equals `x`, it stores `(r, c)`. The final list is sorted first by row ascending, then by column descending (achieved with `key=lambda coord: (coord[0], -coord[1])`). Empty lists or rows are handled naturally by the nested loops.

```python
def get_row(lst, x):
    coords = []
    for r, row in enumerate(lst):
        for c, val in enumerate(row):
            if val == x:
                coords.append((r, c))
    coords.sort(key=lambda coord: (coord[0], -coord[1]))
    return coords
```


Edge cases: an empty array has no first/last index, so we return a copy immediately; a single element has the same value at both indices, so the sum is even and it returns a copy of that element. For all other cases, we copy the array first to avoid mutating the input, then sort ascending when the first and last values sum to an odd number, and descending when they sum to an even number.

```python
def sort_array(array):
    if not array:
        return []

    arr_copy = list(array)
    first = arr_copy[0]
    last = arr_copy[-1]

    if (first + last) % 2 != 0:
        arr_copy.sort()
    else:
        arr_copy.sort(reverse=True)

    return arr_copy
```


The examples show a Caesar cipher with a shift of +4 (e.g. 'h'→'l', 'a'→'e', 'g'→'k', 'e'→'i'). The phrase "shift down by two multiplied to two places" is a convoluted way of saying 2 * 2 = 4. Each lowercase letter is shifted forward by 4 modulo 26; non-letters are left unchanged.

```python
def encrypt(s):
    result = []
    for char in s:
        if 'a' <= char <= 'z':
            result.append(chr((ord(char) - ord('a') + 4) % 26 + ord('a')))
        else:
            result.append(char)
    return ''.join(result)
```


To find the second smallest distinct value, we can collect all unique integers with a set, sort them, and return the element at index 1 if the length is at least 2. Duplicates are collapsed so that `[1, 1]` correctly yields `None` (only one distinct value), and the order of the input does not matter.

```python
def next_smallest(lst):
    distinct = sorted(set(lst))
    if len(distinct) < 2:
        return None
    return distinct[1]
```


The function splits the string on the three sentence delimiters (`.`, `?`, `!`) and checks each resulting sentence. A sentence is counted as a "boredom" if it starts with the word "I" (case-sensitive, as per the examples). Leading and trailing whitespace is stripped from each sentence before the check so that sentences like " I love this" still count.

```python
import re

def is_bored(S):
    sentences = re.split(r'[.?!]', S)
    count = 0
    for sentence in sentences:
        sentence = sentence.strip()
        if sentence.startswith("I "):
            count += 1
    return count
```


The function first checks whether all three inputs are integers using `isinstance(n, int)`; if any input is a float or other type, it returns `False` immediately. Then it tests the three possible pairings: `x == y + z`, `y == x + z`, and `z == x + y`. If any of those equalities holds, it returns `True`; otherwise, it returns `False`.

```python
def any_int(x, y, z):
    if not (isinstance(x, int) and isinstance(y, int) and isinstance(z, int)):
        return False
    return x == y + z or y == x + z or z == x + y
```


ine 31, in check
    assert candidate('Mudasir') == 'mWDCSKR', "This prints if this assert fails 2 (good for debugging!)"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: This prints if this assert fails 2 (good for debugging!)

The function processes each character in the message: non-letters are left unchanged, letters have their case swapped, and vowels (a, e, i, o, u) are shifted two positions forward in the alphabet while preserving the swapped case. Vowel mapping: a→c, e→g, i→k, o→q, u→w.

```python
def encode(message):
    vowel_map = {'a': 'c', 'e': 'g', 'i': 'k', 'o': 'q', 'u': 'w'}
    result = []
    for char in message:
        if char.isalpha():
            swapped = char.swapcase()
            if swapped in vowel_map:
                result.append(vowel_map[swapped])
            else:
                result.append(swapped)
        else:
            result.append(char)
    return ''.join(result)
```


The function first filters the list for prime numbers (integers greater than 1 with no divisors other than 1 and themselves), identifies the maximum among them, and then sums its decimal digits. For the given examples, the largest primes are 181 (1+8+1=10), 4597 (4+5+9+7=25), 5107 (5+1+0+7=13), 83 (8+3=11), and 7 (7), which match the expected outputs.

```python
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

def skjkasdkd(lst):
    primes = [x for x in lst if is_prime(x)]
    if not primes:
        return 0
    largest_prime = max(primes)
    return sum(int(digit) for digit in str(largest_prime))
```


Edge cases: an empty dictionary must return False; non-string keys must return False; mixed case (some lower, some upper) must return False; all keys must be strings for either case to hold. Approach: validate every key is a string, then check if every key equals its lower() or every key equals its upper().

```python
def check_dict_case(dict):
    if not dict:
        return False

    keys = list(dict.keys())
    if not all(isinstance(k, str) for k in keys):
        return False

    all_lower = all(k == k.lower() for k in keys)
    all_upper = all(k == k.upper() for k in keys)

    return all_lower or all_upper
```


The function needs to return all prime numbers strictly less than `n`. Edge cases: `n <= 2` has no primes below it, so return `[]`; `n = 0` and `n = 1` are handled the same way. For larger `n`, a simple primality test checks divisibility from 2 up to `sqrt(k)` for each candidate `k` in `[2, n-1]`. Complexity is O(n·√n) in the worst case, which is fine for the given examples.

```python
def count_up_to(n):
    primes = []
    for k in range(2, n):
        is_prime = True
        for i in range(2, int(k**0.5) + 1):
            if k % i == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(k)
    return primes
```


ders/0l/75d7q65918d_j14rb3j30dlm0000gn/T/tmpqum5pnlh/cand.py", line 21, in check
    assert candidate(148, 412) == 16, "First test error: " + str(candidate(148, 412))
           ^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: First test error: 6

To get the unit digit of an integer, we take the absolute value and use modulo 10 (negative numbers would otherwise yield negative remainders in Python). We then multiply those two digits and take modulo 10 again to return only the unit digit of the product.

```python
def multiply(a, b):
    unit_a = abs(a) % 10
    unit_b = abs(b) % 10
    return (unit_a * unit_b) % 10
```


The function iterates over even indices of the string (`range(0, len(s), 2)`), checks whether the character at that index is an uppercase vowel (`A, E, I, O, U`), and increments a counter when it is. This matches the examples: in `'aBCdEf'`, only index 4 (`'E'`) counts; in `'dBBE'`, index 2 is `'B'` and index 0 is `'d'`, so the result is 0.

```python
def count_upper(s):
    vowels = {'A', 'E', 'I', 'O', 'U'}
    count = 0
    for i in range(0, len(s), 2):
        if s[i] in vowels:
            count += 1
    return count
```


The function parses the input string as a float and uses the standard rounding rule: round to the nearest integer, and when the fractional part is exactly 0.5, round away from zero (up for positive, down for negative). This is achieved by taking the floor of `value + 0.5` for positive numbers and the ceiling of `value - 0.5` for negative numbers, which handles the equidistant case correctly.

```python
def closest_integer(value):
    num = float(value)
    if num >= 0:
        return int(num + 0.5)
    else:
        return int(num - 0.5)
```


The sequence starts at `n` and increments by 2 at each step, which is equivalent to taking the next odd number when `n` is odd and the next even number when `n` is even. We can build the list by starting with `n` and repeatedly adding 2 for `n` levels.

```python
def make_a_pile(n):
    pile = []
    current = n
    for _ in range(n):
        pile.append(current)
        current += 2
    return pile
```


The function needs to split on both commas and spaces while removing any resulting empty strings (e.g. from ", " or multiple spaces). Replacing commas with spaces first, then calling `split()`, handles all cases uniformly.

```python
def words_string(s):
    return s.replace(',', ' ').split()
```


Edge cases: if x > y, the range is empty and we return -1; if y is odd, the largest even candidate is y - 1; if y is even, it is the answer. We only need to check the upper end of the range because we want the *biggest* even integer.

```python
def choose_num(x, y):
    if x > y:
        return -1
    if y % 2 == 0:
        return y
    candidate = y - 1
    return candidate if candidate >= x else -1
```


The average of an arithmetic progression from `n` to `m` is simply `(n + m) / 2`. Rounding to the nearest integer is achieved with `round()`, which rounds to the nearest even number on ties (e.g. 1.5 → 2, 2.5 → 2), matching standard Python rounding. The result is then formatted with `bin()` to include the `0b` prefix.

```python
def rounded_avg(n, m):
    if n > m:
        return -1
    avg = round((n + m) / 2)
    return bin(avg)
```


For each integer, convert it to a string and check every character; if any digit is even (`'0', '2', '4', '6', '8'`), the number is excluded. The remaining numbers are collected and returned as a sorted list.

```python
def unique_digits(x):
    result = []
    for num in x:
        s = str(num)
        if all(int(digit) % 2 != 0 for digit in s):
            result.append(num)
    return sorted(result)
```


The function filters the input to keep only integers in the range [1, 9], sorts them ascending, reverses that list, and maps each digit to its English word using a lookup table. Empty input or arrays with no valid digits naturally result in an empty list.

```python
def by_length(arr):
    names = [
        "One", "Two", "Three", "Four", "Five",
        "Six", "Seven", "Eight", "Nine"
    ]
    valid = [x for x in arr if 1 <= x <= 9]
    valid.sort()
    valid.reverse()
    return [names[x - 1] for x in valid]
```


The function builds a list of length `n` where each index `i` (from 0 to `n-1`) maps to a value based on `i+1` (since the problem states `i` starts from 1). For even `i+1`, we compute the factorial of `i+1`; for odd `i+1`, we compute the triangular sum `(i+1)*(i+2)//2`. The factorial is computed iteratively per element, which is fine for typical `n`.

```python
def f(n):
    result = []
    for i in range(n):
        val = i + 1
        if val % 2 == 0:
            fact = 1
            for j in range(1, val + 1):
                fact *= j
            result.append(fact)
        else:
            result.append(val * (val + 1) // 2)
    return result
```


Iterate through every integer from 1 to n inclusive. For each number, convert it to a string and compare it to its reverse to determine if it is a palindrome. If it is, increment either the even or odd counter based on whether the number is divisible by 2. With n up to 1000, this O(n·d) approach (where d is the number of digits) is well within limits.

```python
def even_odd_palindrome(n):
    even_count = 0
    odd_count = 0
    for i in range(1, n + 1):
        s = str(i)
        if s == s[::-1]:
            if i % 2 == 0:
                even_count += 1
            else:
                odd_count += 1
    return (even_count, odd_count)
```


For each number, we treat the first digit as signed (negative if the number is negative) and all subsequent digits as positive. We sum those signed digits and count how many numbers have a sum strictly greater than 0. Negative numbers with a leading negative digit often have a negative total sum, while positive numbers have a positive total sum.

```python
def count_nums(arr):
    count = 0
    for num in arr:
        s = str(num)
        digits = []
        if s[0] == '-':
            digits.append(-int(s[1]))
            digits.extend(int(d) for d in s[2:])
        else:
            digits.append(int(s[0]))
            digits.extend(int(d) for d in s[1:])
        if sum(digits) > 0:
            count += 1
    return count
```


A right shift preserves the cyclic order of the elements. Therefore, the array can be sorted by right shifts if and only if it is already a cyclic shift of the sorted version. With unique elements, this is equivalent to checking that there is at most one index where `arr[i] > arr[i+1]` (including the wrap-around from the last element to the first), and that the last element is smaller than the first whenever that drop occurs.

```python
def move_one_ball(arr):
    if not arr:
        return True

    n = len(arr)
    drops = []
    for i in range(n):
        if arr[i] > arr[(i + 1) % n]:
            drops.append(i)

    if len(drops) == 0:
        return True
    if len(drops) == 1:
        i = drops[0]
        return arr[i + 1] < arr[i]
    return False
```


To make every element in `lst1` even, each odd number currently in `lst1` must be replaced by an even number from `lst2`. The total number of even values available to fill those slots is the count of even numbers in `lst2` plus the even numbers already in `lst1` (since those can stay). If that total is at least the number of odd elements in `lst1`, the transformation is possible.

```python
def exchange(lst1, lst2):
    odd_in_lst1 = sum(1 for x in lst1 if x % 2 != 0)
    even_in_lst2 = sum(1 for x in lst2 if x % 2 == 0)
    even_in_lst1 = len(lst1) - odd_in_lst1

    if even_in_lst1 + even_in_lst2 >= odd_in_lst1:
        return "YES"
    return "NO"
```


Count each letter with a frequency map, find the maximum count, and collect every letter that reaches that maximum. An empty input string splits into an empty list, so the max over an empty sequence is handled by returning `{}`.

```python
def histogram(test):
    letters = test.split()
    if not letters:
        return {}

    counts = {}
    for letter in letters:
        counts[letter] = counts.get(letter, 0) + 1

    max_count = max(counts.values())
    return {letter: count for letter, count in counts.items() if count == max_count}
```


The approach is to build the result string by keeping only characters in `s` that do not appear in `c` (using a set for O(1) membership checks), then compare that result to its reverse to determine whether it is a palindrome.

```python
def reverse_delete(s, c):
    chars_to_remove = set(c)
    result = "".join(char for char in s if char not in chars_to_remove)
    is_palindrome = result == result[::-1]
    return (result, is_palindrome)
```


The function iterates over each digit string, counts how many digits are odd (1, 3, 5, 7, 9), and builds the required sentence by replacing the indices `i` in the template with that count. Each output string is formatted with the count in four positions: after "elements", in "str[count]g", as the standalone number, and after "the".

```python
def odd_count(lst):
    result = []
    for s in lst:
        odd_count = sum(1 for digit in s if int(digit) % 2 != 0)
        result.append(
            f"the number of odd elements {odd_count}n the str{odd_count}g {odd_count} of the {odd_count}nput."
        )
    return result
```


This is a classic variation of Kadane's algorithm. Instead of maximizing the subarray sum, we track the minimum sum ending at each index. At each step, we either extend the previous minimum subarray or start a new one from the current element, whichever is smaller. The overall minimum across all ending positions is the answer.

```python
def minSubArraySum(nums):
    if not nums:
        return 0

    min_ending_here = nums[0]
    min_so_far = nums[0]

    for i in range(1, len(nums)):
        min_ending_here = min(nums[i], min_ending_here + nums[i])
        min_so_far = min(min_so_far, min_ending_here)

    return min_so_far
```


For each row, the total water is the count of 1s. A bucket of capacity `capacity` can remove up to `capacity` units per trip, so a row with `w` units needs `ceil(w / capacity)` bucket lowers. Summing these values across all rows gives the total number of bucket lowers.

```python
import math

def max_fill(grid, capacity):
    total_lowers = 0
    for row in grid:
        water = sum(row)
        total_lowers += math.ceil(water / capacity)
    return total_lowers
```


The sort key is a tuple `(bin(x).count('1'), x)`: the first element is the number of set bits (ascending), and the second is the decimal value as a tie-breaker (also ascending). Python's `sorted` uses lexicographical tuple comparison, so this matches both rules in one pass.

```python
def sort_array(arr):
    return sorted(arr, key=lambda x: (bin(x).count('1'), x))
```


Split the string into words and count consonants in each word by checking each letter against the set of 21 English consonants (case-insensitive). Words with exactly `n` consonants are collected in order. Empty strings or strings with no matches naturally return an empty list.

```python
def select_words(s, n):
    consonants = set("bcdfghjklmnpqrstvwxyz")
    words = s.split()
    result = []
    for word in words:
        count = sum(1 for char in word if char.lower() in consonants)
        if count == n:
            result.append(word)
    return result
```


/0l/75d7q65918d_j14rb3j30dlm0000gn/T/tmpikchbuwx/cand.py", line 16, in get_closest_vowel
    if word[i - 1] not in vowels and word[i + 1] not in vowels:
                                     ~~~~^^^^^^^
IndexError: string index out of range

Scan the word from right to left and look for a vowel that is immediately flanked by consonants on both sides. The first such vowel encountered is the closest from the right. Vowels at the very beginning or end of the word are excluded because they lack a consonant on one side.

```python
def get_closest_vowel(word):
    vowels = set("aeiouAEIOU")
    for i in range(len(word) - 1, 0, -1):
        if word[i] in vowels:
            if word[i - 1] not in vowels and word[i + 1] not in vowels:
                return word[i]
    return ""
```


There are only two possible concatenations: `lst[0] + lst[1]` and `lst[1] + lst[0]`. For each, we can check balance with a counter: increment on `(` and decrement on `)`, and if the counter ever goes negative or ends non-zero, the string is invalid. If either order is valid, return `'Yes'`; otherwise `'No'`.

```python
def match_parens(lst):
    def is_balanced(s):
        balance = 0
        for ch in s:
            if ch == '(':
                balance += 1
            else:
                balance -= 1
            if balance < 0:
                return False
        return balance == 0

    if is_balanced(lst[0] + lst[1]) or is_balanced(lst[1] + lst[0]):
        return 'Yes'
    return 'No'
```


The simplest correct approach is to sort the entire array in ascending order and take the last `k` elements. Sorting handles duplicates correctly (Example 2) and negative numbers naturally (Example 1). The result is already sorted because the input array was sorted.

```python
def maximum(arr, k):
    return sorted(arr)[-k:] if k > 0 else []
```


The function iterates through the list with indices and adds each element to the total only when the index is even (0, 2, 4, ...) and the value itself is odd. This matches the problem's definition of "even positions" as 0-based indexing (position 0 is the first element).

```python
def solution(lst):
    total = 0
    for i in range(len(lst)):
        if i % 2 == 0 and lst[i] % 2 != 0:
            total += lst[i]
    return total
```


The function considers only the first `k` elements of `arr`. For each element, it checks how many digits it has by converting it to a string and taking the absolute value (so negative numbers are counted by their digit magnitude, e.g. -21 has 2 digits). If that count is 1 or 2, the element is added to the running total.

```python
def add_elements(arr, k):
    total = 0
    for num in arr[:k]:
        if len(str(abs(num))) <= 2:
            total += num
    return total
```


The function generates the Collatz sequence iteratively until it reaches 1, collecting only odd terms. Each step applies the rule: if the current term is even, divide by 2; if odd, compute 3n + 1. The final list is sorted in increasing order as required.

```python
def get_odd_collatz(n):
    odd_numbers = []
    while n != 1:
        if n % 2 != 0:
            odd_numbers.append(n)
            n = 3 * n + 1
        else:
            n = n // 2
    odd_numbers.append(1)
    return sorted(odd_numbers)
```


The function first checks that the input is a non-empty string and matches the exact `mm-dd-yyyy` format with hyphens. It then parses the three numeric components and validates the month (1–12) and the day against the specific rules given: 31 days for months 1,3,5,7,8,10,12; 30 days for months 4,6,9,11; and 29 days for February (month 2).

```python
def valid_date(date):
    if not date or not isinstance(date, str):
        return False

    parts = date.split('-')
    if len(parts) != 3:
        return False

    try:
        month = int(parts[0])
        day = int(parts[1])
        year = int(parts[2])
    except ValueError:
        return False

    if not (1 <= month <= 12):
        return False

    if month in (1, 3, 5, 7, 8, 10, 12):
        if not (1 <= day <= 31):
            return False
    elif month in (4, 6, 9, 11):
        if not (1 <= day <= 30):
            return False
    elif month == 2:
        if not (1 <= day <= 29):
            return False
    else:
        return False

    return True
```


The function follows the three-tier fallback logic: first try splitting on whitespace; if the string contains no whitespace, try splitting on commas; if it contains neither, count lowercase letters whose 0-indexed alphabet position is odd (b, d, f, ...).

```python
def split_words(txt):
    if any(c.isspace() for c in txt):
        return txt.split()
    if ',' in txt:
        return [word for word in txt.split(',') if word]
    return sum(1 for c in txt if c.islower() and (ord(c) - ord('a')) % 2 == 1)
```


The function checks two conditions: first, that every element is less than or equal to the next (ascending order); second, that no value appears more than twice (duplicate count). A single pass with a frequency counter handles both in O(n) time.

```python
def is_sorted(lst):
    counts = {}
    for i in range(len(lst)):
        val = lst[i]
        counts[val] = counts.get(val, 0) + 1
        if counts[val] > 2:
            return False
        if i > 0 and lst[i] < lst[i - 1]:
            return False
    return True
```


The intersection of two closed intervals `(s1, e1)` and `(s2, e2)` is `(max(s1, s2), min(e1, e2))`. If the start is greater than the end, there is no intersection. Otherwise, the length is `end - start`. A prime number must be at least 2, so lengths 0 and 1 are not prime. For lengths ≥ 2, we check primality by trial division up to the square root.

```python
def intersection(interval1, interval2):
    s1, e1 = interval1
    s2, e2 = interval2

    start = max(s1, s2)
    end = min(e1, e2)

    if start > end:
        return "NO"

    length = end - start

    if length < 2:
        return "NO"

    for i in range(2, int(length**0.5) + 1):
        if length % i == 0:
            return "NO"

    return "YES"
```


The function first handles the empty array edge case by returning `None`. For a non-empty array, it computes two values: the sum of absolute values (`sum(abs(x) for x in arr)`) and the product of signs (`1` for positive, `-1` for negative, `0` for zero). If any element is zero, the sign product becomes zero, and the final result is 0. Otherwise, the magnitude sum is multiplied by the combined sign of all elements.

```python
def prod_signs(arr):
    if not arr:
        return None

    magnitude_sum = sum(abs(x) for x in arr)
    sign_product = 1
    for x in arr:
        if x > 0:
            sign_product *= 1
        elif x < 0:
            sign_product *= -1
        else:
            sign_product = 0
            break

    return magnitude_sum * sign_product
```


We want the lexicographically smallest sequence of k cell values. The first element should be as small as possible, so we start at the cell containing 1. From there, at each step we greedily pick the neighbor with the smallest value. Because we can revisit cells, the best move is always the minimum neighbor; if that neighbor is the cell we just came from, we can return there and repeat that value for all remaining steps. This greedy choice is optimal because any other choice would produce a lexicographically larger sequence at the first differing index.

```python
def minPath(grid, k):
    n = len(grid)
    # Find the starting cell (value 1)
    start = None
    for r in range(n):
        for c in range(n):
            if grid[r][c] == 1:
                start = (r, c)
                break
        if start:
            break

    path = [1]
    curr_r, curr_c = start
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

    for _ in range(k - 1):
        best_val = float('inf')
        best_pos = None
        for dr, dc in directions:
            nr, nc = curr_r + dr, curr_c + dc
            if 0 <= nr < n and 0 <= nc < n:
                if grid[nr][nc] < best_val:
                    best_val = grid[nr][nc]
                    best_pos = (nr, nc)
        path.append(best_val)
        curr_r, curr_c = best_pos

    return path
```


~~~~~^^^
  File "/var/folders/0l/75d7q65918d_j14rb3j30dlm0000gn/T/tmplksythi6/cand.py", line 27, in tri
    res[i] = res[i - 1] + res[i - 2] + res[i + 1]
                                       ~~~^^^^^^^
IndexError: list index out of range

The recurrence for odd `n` depends on `tri(n+1)`, which would normally cause infinite recursion. However, the examples resolve this: `tri(2)=2`, `tri(4)=3`, and `tri(3)=tri(2)+tri(1)+tri(4)=8`. This implies the sequence is built iteratively from the base cases `tri(1)=3`, `tri(2)=2`, and `tri(4)=3`, with odd terms computed as the sum of the three neighbors. For `n=0`, the only value is `tri(0)`, which is not defined by the rules but must be the first element of the list; the examples start at index 1, so we prepend a placeholder (0) for index 0.

```python
def tri(n):
    if n == 0:
        return [0]

    res = [0] * (n + 1)
    res[1] = 3
    if n >= 2:
        res[2] = 2
    if n >= 4:
        res[4] = 3

    for i in range(1, n + 1):
        if i % 2 == 0:
            res[i] = 1 + i // 2
        else:
            res[i] = res[i - 1] + res[i - 2] + res[i + 1]

    return res
```


The function iterates through each digit of `n` by converting it to a string. Odd digits are multiplied into a running product initialized at 1; a flag tracks whether any odd digit was found. If no odd digits exist, the function returns 0 as specified.

```python
def digits(n):
    product = 1
    has_odd = False
    for digit_char in str(n):
        digit = int(digit_char)
        if digit % 2 != 0:
            product *= digit
            has_odd = True
    return product if has_odd else 0
```


iz9h/cand.py", line 29, in check
    assert candidate('[[]]') == True, "This prints if this assert fails 1 (good for debugging!)"
           ^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: This prints if this assert fails 1 (good for debugging!)

The problem asks whether the string contains a valid bracket subsequence with nesting. A valid bracket subsequence is a subsequence that can be fully matched as balanced pairs; nesting occurs when one pair is contained inside another (e.g. `[[]]`).

The simplest valid bracket subsequence is a single pair `[]`. Any valid subsequence with nesting must contain at least one pair that is fully enclosed by another pair, which is equivalent to the string containing the substring `[[]` or `[[]` as a subsequence. More directly, nesting exists in a valid subsequence if and only if there are four indices i < j < k < l such that the brackets at those positions form `[ [ ] ]`.

We can check this with a single pass: track the maximum depth of open brackets seen so far. When we see `[` at depth `d`, we record it; when we see `]` at depth `d+1`, we check if we previously saw a `[` at depth `d` — that forms a nested pair.

```python
def is_nested(string):
    open_depths = []
    for char in string:
        if char == '[':
            open_depths.append(len(open_depths))
        elif char == ']':
            if open_depths:
                depth = len(open_depths) - 1
                open_depths.pop()
                if depth >= 0 and depth in open_depths:
                    return True
    return False
```


For each number, we apply `math.ceil` to round it up to the nearest integer, square that integer, and add it to a running total. This matches all examples: `[1.4, 4.2, 0]` becomes `2^2 + 5^2 + 0^2 = 29`, and `[-2.4, 1, 1]` becomes `(-2)^2 + 1^2 + 1^2 = 6`.

```python
import math

def sum_squares(lst):
    return sum(math.ceil(x) ** 2 for x in lst)
```


The function must return `True` only when the last character of `txt` is a letter AND it is not part of a word (i.e., it is a single letter surrounded by spaces or at the string boundaries, not adjacent to other non-space characters).

Edge cases:
- Empty string: return `False`.
- Trailing space: the last character is `' '`, not a letter → `False`.
- Last word with multiple letters (e.g. "pie"): the last letter is adjacent to another letter → `False`.
- Single letter word (e.g. "e"): the last letter has no non-space neighbors → `True`.

Approach: check `txt[-1]` is a letter, then verify that both `txt[-2]` (if it exists) and `txt[-3]` (if it exists) are spaces.

```python
def check_if_last_char_is_a_letter(txt):
    if not txt or not txt[-1].isalpha():
        return False

    # The last character is a letter; it is not part of a word if
    # it has no non-space neighbors.
    if len(txt) == 1:
        return True

    # Check the character immediately before the last one
    if txt[-2] != ' ':
        return False

    # If there is a character before that, it must also be a space
    if len(txt) >= 3 and txt[-3] != ' ':
        return False

    return True
```


module>
    check(can_arrange)
    ~~~~~^^^^^^^^^^^^^
  File "/var/folders/0l/75d7q65918d_j14rb3j30dlm0000gn/T/tmp3y49urzh/cand.py", line 25, in check
    assert candidate([4,8,5,7,3])==4
           ^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError

Scan the array from left to right starting at index 1 and compare each element to its predecessor. The first time an element is strictly smaller than the previous one, that index is the answer (since we want the largest index that satisfies the condition, and the examples imply we stop at the first violation). If the array is strictly increasing, return -1.

```python
def can_arrange(arr):
    for i in range(1, len(arr)):
        if arr[i] < arr[i - 1]:
            return i
    return -1
```


The function filters the list into two groups: negative integers (strictly less than 0) and positive integers (strictly greater than 0). Zero is excluded from both. For each group, it returns the maximum of negatives (the negative value closest to 0) and the minimum of positives, or `None` if the group is empty.

```python
def largest_smallest_integers(lst):
    negatives = [x for x in lst if x < 0]
    positives = [x for x in lst if x > 0]

    a = max(negatives) if negatives else None
    b = min(positives) if positives else None

    return (a, b)
```


To compare the values, each input is normalized to a float: integers and floats are used directly, and strings are parsed by replacing `,` with `.` before conversion. If the normalized values are equal, the function returns `None`; otherwise it returns the original variable that holds the larger normalized value.

```python
def compare_one(a, b):
    def to_float(val):
        if isinstance(val, str):
            return float(val.replace(",", "."))
        return float(val)

    fa = to_float(a)
    fb = to_float(b)

    if fa == fb:
        return None
    return a if fa > fb else b
```


The smallest positive even number is 2, so the minimum sum of four such numbers is 2 + 2 + 2 + 2 = 8. Any number less than 8 cannot be represented this way. For n ≥ 8, the sum of four even numbers must itself be even, so odd n are excluded. Every even n ≥ 8 can be written as 8 + 2 + 2 + (n - 8), where n - 8 is even and non-negative; if n - 8 is 0, we use four 2s; otherwise we use two 2s and two other even numbers (e.g. 2 and n-6).

```python
def is_equal_to_sum_even(n):
    return n >= 8 and n % 2 == 0
```


The Brazilian factorial is the product of all factorials from 1! up to n!. We can compute it in O(n²) by iteratively building each factorial and multiplying it into the running total. For n=4, the terms are 1!·2!·3!·4! = 1·2·6·24 = 288.

```python
def special_factorial(n):
    result = 1
    current_factorial = 1
    for i in range(1, n + 1):
        current_factorial *= i
        result *= current_factorial
    return result
```


e("   Exa 1 2 2 mple") == "-Exa_1_2_2_mple", "This prints if this assert fails 4 (good for debugging!)"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: This prints if this assert fails 4 (good for debugging!)

The function first checks whether the input contains any run of three or more consecutive spaces. If it does, the entire string is processed by collapsing every sequence of one or more spaces into a single hyphen; otherwise, every individual space is replaced with an underscore. This matches the examples: single spaces become underscores, while the triple-space case triggers the hyphen rule.

```python
import re

def fix_spaces(text):
    if re.search(r' {3,}', text):
        return re.sub(r' +', '-', text)
    return text.replace(' ', '_')
```


The function validates the filename by counting digits, splitting on the dot, and checking the prefix and extension against the given rules. Edge cases like multiple dots, no dots, empty prefixes, or non-latin starts are handled by the explicit conditions.

```python
def file_name_check(file_name):
    # Count digits in the entire filename
    digit_count = sum(1 for char in file_name if char.isdigit())
    if digit_count > 3:
        return 'No'

    # Split on dot and ensure there is exactly one dot
    parts = file_name.split('.')
    if len(parts) != 2:
        return 'No'

    prefix, extension = parts

    # Prefix must not be empty and must start with a latin letter
    if not prefix or not prefix[0].isalpha():
        return 'No'

    # Extension must be one of the three allowed values
    if extension not in ['txt', 'exe', 'dll']:
        return 'No'

    return 'Yes'
```


The function iterates through the list with `enumerate` to track each index. For each element, it applies the transformation rules in order: if the index is a multiple of 3, the value is squared; otherwise, if it is a multiple of 4, it is cubed; otherwise the value remains unchanged. The transformed values are then summed and returned. An empty list naturally yields 0.

```python
def sum_squares(lst):
    total = 0
    for i, val in enumerate(lst):
        if i % 3 == 0:
            total += val ** 2
        elif i % 4 == 0:
            total += val ** 3
        else:
            total += val
    return total
```


Split the sentence into words and filter each word whose length is prime. A helper `is_prime` handles the primality check (lengths are small, so trial division is fine). Join the kept words with a single space to preserve original order.

```python
def words_in_sentence(sentence):
    def is_prime(n):
        if n < 2:
            return False
        for i in range(2, int(n**0.5) + 1):
            if n % i == 0:
                return False
        return True

    words = sentence.split()
    result = [word for word in words if is_prime(len(word))]
    return " ".join(result)
```


The product of two fractions is the product of their numerators divided by the product of their denominators. The result is a whole number if and only if the combined denominator divides the combined numerator evenly. We parse each fraction by splitting on the slash, convert the parts to integers, and check `(num_x * num_n) % (den_x * den_n) == 0`.

```python
def simplify(x, n):
    num_x, den_x = map(int, x.split('/'))
    num_n, den_n = map(int, n.split('/'))
    return (num_x * num_n) % (den_x * den_n) == 0
```


The key is to use a stable sort with a single sort key: the sum of the absolute digits. Python'.s `sorted()` is stable, so when digit sums tie, the original relative order is preserved automatically. For negative numbers, we sum the digits of the absolute value (e.g. -12 → 1+2=3), which matches the example.

```python
def order_by_points(nums):
    def digit_sum(n):
        return sum(int(d) for d in str(abs(n)))

    return sorted(nums, key=digit_sum)
```


The function iterates through each number and applies three checks: the value must be strictly greater than 10, and the first and last digits must both be odd. Negative numbers are handled by taking the absolute value before digit extraction, so `-73` is treated as `73` (first digit 7, last digit 3 — both odd). Each number is converted to a string for O(d) digit access where d is the number of digits.

```python
def specialFilter(nums):
    count = 0
    for num in nums:
        if num > 10:
            s = str(abs(num))
            first = int(s[0])
            last = int(s[-1])
            if first % 2 != 0 and last % 2 != 0:
                count += 1
    return count
```


The values are defined as `a[i] = i^2 - i + 1`. Modulo 3, this simplifies:
- If `i ≡ 0 (mod 3)`, then `a[i] ≡ 0 - 0 + 1 = 1`.
- If `i ≡ 1 (mod 3)`, then `a[i] ≡ 1 - 1 + 1 = 1`.
- If `i ≡ 2 (mod 3)`, then `a[i] ≡ 4 - 2 + 1 = 3 ≡ 0`.

So every element is either 0 or 1 modulo 3. For the sum of three elements to be a multiple of 3, the only valid combination is three 0s (0+0+0=0) or three 1s (1+1+1=3). We count how many indices fall into each remainder class and use combinations: `C(count0, 3) + C(count1, 3)`.

```python
def get_max_triples(n):
    count0 = 0
    count1 = 0
    for i in range(1, n + 1):
        rem = (i * i - i + 1) % 3
        if rem == 0:
            count0 += 1
        else:
            count1 += 1

    def combinations_3(c):
        if c < 3:
            return 0
        return c * (c - 1) * (c - 2) // 6

    return combinations_3(count0) + combinations_3(count1)
```


The planets are ordered by distance from the Sun. The function first validates both inputs against the canonical list; if either is invalid, it returns an empty tuple. Otherwise, it identifies the start and end indices and returns all planets strictly between them in order.

```python
def bf(planet1, planet2):
    planets = (
        "Mercury",
        "Venus",
        "Earth",
        "Mars",
        "Jupiter",
        "Saturn",
        "Uranus",
        "Neptune",
    )

    if planet1 not in planets or planet2 not in planets:
        return ()

    idx1 = planets.index(planet1)
    idx2 = planets.index(planet2)

    start, end = min(idx1, idx2), max(idx1, idx2)

    return tuple(planets[i] for i in range(start + 1, end))
```


The function filters the list to keep only strings with even lengths, then sorts them using a tuple key: `(len(word), word)`. This primary sort by length and secondary alphabetical sort on ties matches the requirement. The problem statement also mentions "all words will have the same length" as an assumption, which would make the length sort trivial but the tie-breaking still applies.

```python
def sorted_list_sum(lst):
    even_length_strings = [word for word in lst if len(word) % 2 == 0]
    return sorted(even_length_strings, key=lambda word: (len(word), word))
```


The function checks whether `n` is prime by first handling numbers less than 2 (not prime), then testing divisibility from 2 up to the square root of `n`. If no divisor is found, `n` is prime and the function returns `x`; otherwise it returns `y`.

```python
def x_or_y(n, x, y):
    if n < 2:
        return y
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return y
    return x
```


The function filters the list for values that are integers, non-negative, and odd, then sums their squares. The examples show that 0 is treated as even (0² = 0), and negative numbers are ignored entirely. Empty lists or lists with no valid odd integers naturally sum to 0.

```python
def double_the_difference(lst):
    return sum(x**2 for x in lst if isinstance(x, int) and x >= 0 and x % 2 != 0)
```


For each index, the error is the absolute difference between the score and the guess, which equals 0 when they match. A list comprehension over the zipped arrays computes this in O(n) time.

```python
def compare(game, guess):
    return [abs(score - g) for score, g in zip(game, guess)]
```


The strength of each extension is calculated by counting uppercase letters (`CAP`) and lowercase letters (`SM`) and taking the difference `CAP - SM`. We iterate through the extensions in order, keeping the first extension that achieves the maximum strength found so far, which naturally handles ties by favoring the earlier extension. The result is formatted as `class_name.best_extension`.

```python
def Strongest_Extension(class_name, extensions):
    best_extension = None
    max_strength = float('-inf')

    for extension in extensions:
        cap = sum(1 for char in extension if char.isupper())
        sm = sum(1 for char in extension if char.islower())
        strength = cap - sm

        if strength > max_strength:
            max_strength = strength
            best_extension = extension

    return f"{class_name}.{best_extension}"
```


For each rotation of `b`, we check whether that rotation appears as a substring in `a`. A word of length `n` has `n` distinct rotations, which can be generated by slicing `b` at every index and concatenating the two parts in reversed order. For each rotation, we use Python's `in` operator, which is the standard way to check substring membership.

```python
def cycpattern_check(a, b):
    n = len(b)
    for i in range(n):
        rotation = b[i:] + b[:i]
        if rotation in a:
            return True
    return False
```


The function treats the number as a sequence of digits by taking its absolute value and iterating over each character in its string representation. Each digit is converted back to an integer and checked with modulo 2; even digits increment the first counter, odd digits increment the second. Negative signs are ignored via `abs()`, and the result is returned as a tuple `(even, odd)`.

```python
def even_odd_count(num):
    even = 0
    odd = 0
    for digit in str(abs(num)):
        if int(digit) % 2 == 0:
            even += 1
        else:
            odd += 1
    return (even, odd)
```


The standard greedy approach works here: iterate through a list of Roman numeral values and symbols from largest to smallest, subtracting each value from the number while appending the symbol. The subtraction order handles subtractive pairs like 4 (iv), 9 (ix), 40 (xl), 90 (xc), 400 (cd), and 900 (cm) naturally. The result is lowercased at the end.

```python
def int_to_mini_roman(number):
    values = [
        (1000, 'm'), (900, 'cm'), (500, 'd'), (400, 'cd'),
        (100, 'c'), (90, 'xc'), (50, 'l'), (40, 'xl'),
        (10, 'x'), (9, 'ix'), (5, 'v'), (4, 'iv'), (1, 'i')
    ]
    result = []
    for value, symbol in values:
        while number >= value:
            result.append(symbol)
            number -= value
    return ''.join(result)
```


A triangle is right-angled if and only if the square of the longest side equals the sum of the squares of the other two sides (Pythagorean theorem). The function sorts the sides so that `c` is always the hypotenuse candidate, then checks `a² + b² == c²`.

```python
def right_angle_triangle(a, b, c):
    sides = sorted([a, b, c])
    return sides[0]**2 + sides[1]**2 == sides[2]**2
```


For each word, the number of unique characters is `len(set(word))`. We want the word that maximizes this count, and among ties, the lexicographically smallest word. A single `max` over the list with a tuple key `(-unique_count, word)` achieves both: negating the count makes the largest count the minimum value, and the raw word handles lexicographical order as the tie-breaker.

```python
def find_max(words):
    if not words:
        return ""
    return max(words, key=lambda word: (-len(set(word)), word))
```


The rabbit wants to eat `need` more carrots, but can only take what is available in `remaining`. So the amount actually eaten is `min(need, remaining)`. The total eaten becomes `number + eaten`, and the stock decreases by that same amount.

```python
def eat(number, need, remaining):
    eaten = min(need, remaining)
    total = number + eaten
    left = remaining - eaten
    return [total, left]
```


The problem asks to evaluate an infix expression built from two lists: `operator` (n-1 operators) and `operand` (n integers). The example `2 + 3 * 4 - 5` evaluates to 9, which follows standard Python operator precedence (multiplication before addition/subtraction), not left-to-right evaluation.

The cleanest approach is to build the expression as a Python string and use `eval`. Each operand is placed as a literal, and each operator is placed between them. For floor division, we use `//` so `eval` performs integer division rather than float division. Since the inputs are non-negative integers and the operators are fixed, this is safe and correctly respects precedence.

```python
def do_algebra(operator, operand):
    expression = str(operand[0])
    for op, val in zip(operator, operand[1:]):
        if op == '//':
            expression += " // "
        else:
            expression += f" {op} "
        expression += str(val)
    return eval(expression)
```


The function first checks whether the string contains any letters using `isalpha()`. If it does not, the entire string is reversed. Otherwise, each character is processed: letters have their case swapped with `swapcase()`, and non-letter characters are left unchanged.

```python
def solve(s):
    if not any(c.isalpha() for c in s):
        return s[::-1]
    return "".join(c.swapcase() for c in s)
```


The function first checks whether `text` is empty and returns `None` in that case. Otherwise, it encodes the string to UTF-8, computes the MD5 hash using Python's `hashlib`, and returns the hexadecimal representation.

```python
import hashlib

def string_to_md5(text):
    if not text:
        return None
    return hashlib.md5(text.encode('utf-8')).hexdigest()
```


The function first normalizes the range so that `start` is the smaller value and `end` is the larger, which handles cases where `a > b`. It then iterates through every integer in that inclusive range and collects those divisible by 2. Since the loop runs from the smaller to the larger value, the result is already in ascending order.

```python
def generate_integers(a, b):
    start, end = min(a, b), max(a, b)
    return [i for i in range(start, end + 1) if i % 2 == 0]
```