Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Detect whether a linked list has a cycle and return the value where the cycle starts (None if acyclic).

Problem: Detect whether a linked list has a cycle and return the value where the cycle starts (None if acyclic).
class Node:
    def __init__(self, v, nxt=None):
        self.v, self.next = v, nxt
def build(xs):
    head = None
    for x in reversed(xs):
        head = Node(x, head)
    return head
def show(h):
    out = []
    while h:
        out.append(h.v); h = h.next
    return out
def cycle_start(h):
    slow = fast = h
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
        if slow is fast:
            slow = h
            while slow is not fast:
                slow, fast = slow.next, fast.next
            return slow.v
    return None
h = build([3, 8, 5, 1, 9, 6])
n = h
while n.next: n = n.next
n.next = h.next.next
print(cycle_start(h), cycle_start(build([1, 2])))
What is printed?
  1. A. 5 None
  2. B. 8 None
  3. C. 9 None
  4. D. 5 2

Correct answer: A. 5 None

The tail (6) is linked back to the third node (5). After slow and fast meet, restarting one pointer from the head and moving both one step at a time makes them meet exactly at the cycle entry (distance head→entry equals meeting point→entry modulo the cycle length). O(n) time, O(1) space.

More Coding Interview Problems questions

Exams that ask this topic