"""Pattern 4: Prefix sums (often with a hash map).

prefix[i] = nums[0] + ... + nums[i-1]. Any subarray sum is a difference of
two prefixes: sum(nums[i:j]) = prefix[j] - prefix[i]. Store prefixes seen so
far in a hash map to answer "how many subarrays sum to k?" in one pass.
"""

from collections import defaultdict
from itertools import accumulate


class RangeSum:
    """O(n) build, O(1) query for sum(nums[left:right + 1])."""

    def __init__(self, nums: list[int]) -> None:
        self.prefix = [0, *accumulate(nums)]

    def query(self, left: int, right: int) -> int:
        return self.prefix[right + 1] - self.prefix[left]


def subarray_sum_count(nums: list[int], k: int) -> int:
    """Number of contiguous subarrays summing to k (works with negatives)."""
    seen: dict[int, int] = defaultdict(int)
    seen[0] = 1  # the empty prefix
    running = count = 0
    for x in nums:
        running += x
        count += seen[running - k]
        seen[running] += 1
    return count


def longest_balanced_binary(nums: list[int]) -> int:
    """Contiguous array: longest subarray with equal 0s and 1s.

    Map 0 -> -1; a balanced subarray has prefix difference 0, so remember the
    FIRST index where each running sum appeared.
    """
    first_index = {0: -1}
    running = best = 0
    for i, x in enumerate(nums):
        running += 1 if x == 1 else -1
        if running in first_index:
            best = max(best, i - first_index[running])
        else:
            first_index[running] = i
    return best


def product_except_self(nums: list[int]) -> list[int]:
    """Prefix products from the left times suffix products from the right."""
    n = len(nums)
    out = [1] * n
    left = 1
    for i in range(n):
        out[i] = left
        left *= nums[i]
    right = 1
    for i in range(n - 1, -1, -1):
        out[i] *= right
        right *= nums[i]
    return out
