Python coding

First node of the cycle

In a singly linked list, the last node may point back at an earlier node (or at itself), which makes a cycle. Write cycle_start(head): return the node where the cycle begins, or None if the list ends normally. Values can repeat, so compare nodes with is, not by value.

Do not modify the list. Aim for O(1) extra memory.

The tests call the provided run_cycle_start(values, pos): it builds the list, points the last node at index pos (-1 means no cycle) and returns the index of your node, or -1 for None.

  • run_cycle_start([4,8,15,16], 1) → 1
  • run_cycle_start([6,7], 0) → 0
  • run_cycle_start([1,2,3], -1) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

A set of visited nodes solves it with O(n) memory. For O(1), start with a slow and a fast pointer: if there is a cycle, they must meet inside it.

Hint 2

The meeting point is usually not the entry. Move one pointer back to the head and advance both one step at a time: they meet exactly at the entry.

Hint 3

Start both pointers at head. Starting fast one node ahead still detects a cycle, but it breaks the distance argument of the second phase.

Solution and why it works
pythonO(n) · O(1)
# --- your code ---
def cycle_start(head: "ListNode | None") -> "ListNode | None":
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:                 # they met somewhere inside the cycle
            slow = head
            while slow is not fast:      # same speed now: they meet at the entry
                slow = slow.next
                fast = fast.next
            return slow
    return None                          # fast reached the end: no cycle


# --- provided: do not edit ---
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def run_cycle_start(values: list[int], pos: int) -> int:
    nodes = [ListNode(v) for v in values]
    for node, nxt in zip(nodes, nodes[1:]):
        node.next = nxt
    if nodes and pos >= 0:
        nodes[-1].next = nodes[pos]      # the last node points back: a cycle
    links = [node.next for node in nodes]
    found = cycle_start(nodes[0] if nodes else None)
    intact = all(n.val == v and n.next is link for n, v, link in zip(nodes, values, links))
    if not intact:
        raise ValueError("the list was modified: leave every value and link as it was")
    if found is None:
        return -1
    for i, node in enumerate(nodes):
        if node is found:
            return i
    raise ValueError("return a node of the list (or None), not a value or a new node")

Say the entry is a steps from the head and the cycle has c nodes. When the pointers meet, slow has walked s steps and fast 2s, so s is a multiple of c. Then a more steps from the meeting point land on the entry (a + s steps is the entry plus full laps), and so do a steps from the head: walk both at the same speed until they coincide. Traps: returning the meeting point, and starting fast one node ahead, which breaks this arithmetic.