"""Pattern 1: Two pointers.

Two indices move through a sequence, either from both ends towards each other
(sorted arrays, palindromes, "pair with sum") or in the same direction at
different speeds (reader/writer for in-place filtering).
"""


def pair_with_target_sum(nums: list[int], target: int) -> tuple[int, int] | None:
    """Opposite-ends template on a SORTED array: indices of a pair summing to target."""
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return left, right
        if total < target:
            left += 1  # need a bigger sum
        else:
            right -= 1  # need a smaller sum
    return None


def three_sum(nums: list[int]) -> list[list[int]]:
    """All unique triplets summing to zero: sort, fix one value, two-pointer the rest."""
    nums = sorted(nums)
    result: list[list[int]] = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue  # skip duplicate anchors
        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                result.append([nums[i], nums[left], nums[right]])
                left += 1
                right -= 1
                while left < right and nums[left] == nums[left - 1]:
                    left += 1
    return result


def remove_duplicates(nums: list[int]) -> int:
    """Same-direction (reader/writer) template: dedupe a sorted list in place.

    Returns k; nums[:k] holds the unique values.
    """
    write = 0
    for read in range(len(nums)):
        if read == 0 or nums[read] != nums[read - 1]:
            nums[write] = nums[read]
            write += 1
    return write


def max_area(heights: list[int]) -> int:
    """Container with most water: always move the shorter wall inward."""
    left, right = 0, len(heights) - 1
    best = 0
    while left < right:
        best = max(best, (right - left) * min(heights[left], heights[right]))
        if heights[left] < heights[right]:
            left += 1
        else:
            right -= 1
    return best


def is_palindrome(s: str) -> bool:
    """Valid palindrome ignoring non-alphanumerics and case."""
    left, right = 0, len(s) - 1
    while left < right:
        if not s[left].isalnum():
            left += 1
        elif not s[right].isalnum():
            right -= 1
        elif s[left].lower() != s[right].lower():
            return False
        else:
            left += 1
            right -= 1
    return True
