"""Pattern 8: Cyclic sort (index as hash).

When values are in a known range like 1..n, each value v has a "home" index
v - 1. Swap values home until every slot holds its own value or a value that
cannot be placed. Then a single scan reveals what is missing or duplicated.
O(n) time, O(1) extra space.
"""


def cyclic_sort(nums: list[int]) -> list[int]:
    """Place each value v (in 1..n) at index v - 1, in place."""
    i = 0
    while i < len(nums):
        home = nums[i] - 1
        if 0 <= home < len(nums) and nums[i] != nums[home]:
            nums[i], nums[home] = nums[home], nums[i]
        else:
            i += 1
    return nums


def find_disappeared(nums: list[int]) -> list[int]:
    """Values in 1..n that do not appear."""
    cyclic_sort(nums)
    return [i + 1 for i, v in enumerate(nums) if v != i + 1]


def find_duplicates(nums: list[int]) -> list[int]:
    """Values in 1..n that appear twice."""
    cyclic_sort(nums)
    return sorted(v for i, v in enumerate(nums) if v != i + 1)


def first_missing_positive(nums: list[int]) -> int:
    """Smallest positive integer not in nums (ignores values outside 1..n)."""
    cyclic_sort(nums)
    for i, v in enumerate(nums):
        if v != i + 1:
            return i + 1
    return len(nums) + 1


def missing_number(nums: list[int]) -> int:
    """Values 0..n with one missing. The XOR trick needs no sorting at all."""
    result = len(nums)
    for i, v in enumerate(nums):
        result ^= i ^ v
    return result
