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?- A. 5 None
- B. 8 None
- C. 9 None
- 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
- Problem: Reverse the nodes of a linked list k at a time; a final group with fewer than k nodes stays as is. python class Node: def…
- Problem: Add two numbers whose digits are stored in reverse order in linked lists. python class Node: def init(self, v, nxt=None): self.v…
- Problem: An LRU cache of capacity c must support get(key) and put(key, value) in O(1) each, evicting the least recently used key. Which…
- Problem: The function below should check whether a singly linked list is a palindrome in O(1) extra space. python class Node: def…
- Problem: Return the height (number of nodes on the longest root-to-leaf path) of an org-chart tree. Trees are built by build(xs): a…
- Problem: Print the level-order traversal of a tree, one list per level. Trees are built by build(xs): a level-order list where index i has…