"""Pattern 2: Fast and slow pointers (Floyd's tortoise and hare).

One pointer moves one step, the other two steps. If there is a cycle they
must meet inside it; if not, the fast pointer falls off the end. When fast
reaches the end, slow is at the middle.
"""

from templates.structures import ListNode


def has_cycle(head: ListNode | None) -> bool:
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow = slow.next  # type: ignore[union-attr]
        fast = fast.next.next
        if slow is fast:
            return True
    return False


def cycle_start(head: ListNode | None) -> ListNode | None:
    """Return the node where the cycle begins, or None.

    After the meeting point, a pointer from the head and a pointer from the
    meeting point, both moving one step, meet at the cycle entrance.
    """
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow = slow.next  # type: ignore[union-attr]
        fast = fast.next.next
        if slow is fast:
            finder = head
            while finder is not slow:
                finder = finder.next  # type: ignore[union-attr]
                slow = slow.next  # type: ignore[union-attr]
            return finder
    return None


def middle_node(head: ListNode | None) -> ListNode | None:
    """Middle node; for even length returns the second of the two middles."""
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow = slow.next  # type: ignore[union-attr]
        fast = fast.next.next
    return slow


def is_happy(n: int) -> bool:
    """Happy number: the digit-square sequence either reaches 1 or cycles."""

    def step(x: int) -> int:
        return sum(int(d) ** 2 for d in str(x))

    slow, fast = n, step(n)
    while fast != 1 and slow != fast:
        slow = step(slow)
        fast = step(step(fast))
    return fast == 1


def find_duplicate(nums: list[int]) -> int:
    """Values 1..n in n+1 slots: treat i -> nums[i] as a linked list with a cycle."""
    slow = fast = nums[0]
    while True:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break
    finder = nums[0]
    while finder != slow:
        finder = nums[finder]
        slow = nums[slow]
    return finder
