Data Structures & AlgorithmsVery hardAmazon · Microsoft OA
Problem: Floyd's cycle detection on a linked list whose tail points back into the middle. Report the value where slow and fast first meet and the value at the start of the cycle.
Problem: Floyd's cycle detection on a linked list whose tail points back into the middle. Report the value where slow and fast first meet and the value at the start of the cycle.
class N:
def __init__(s, v): s.v, s.nx = v, None
nodes = [N(v) for v in [1, 2, 3, 4, 5, 6]]
for a, b in zip(nodes, nodes[1:]): a.nx = b
nodes[-1].nx = nodes[2]
slow = fast = nodes[0]
while True:
slow, fast = slow.nx, fast.nx.nx
if slow is fast: break
meet = slow.v
p = nodes[0]
while p is not slow: p, slow = p.nx, slow.nx
print(meet, p.v)What is printed?- A. 3 3
- B. 4 3
- C. 6 3
- D. 5 3
Correct answer: D. 5 3
Positions (slow, fast) go (2,3), (3,5), (4,3), (5,5): they meet at value 5. Then a pointer from the head and one from the meeting point, moving one step each, meet at the cycle start 3, because the head-to-start distance equals the meeting-point-to-start distance modulo the cycle length.
More Coding Interview Problems questions
- Problem: Rob houses arranged as a tree (node 0 is the root; parent[i] gives each node's parent). Directly linked houses cannot both be…
- Problem: Keep the k-th largest score of a live leaderboard with a size-k min-heap and log the k-th largest once at least k scores have…
- Problem: From index 0, a[i] is the longest jump allowed from i. Find the minimum number of jumps to reach the last index (greedy BFS by…
- Problem: Split a string into as many parts as possible so that each letter appears in at most one part; return the part sizes. python def…
- How many structurally different binary search trees can be built on the keys 1..7 if the ROOT must be 3?
- Problem: Count the ways to tile a 2 × n board with 2 × 1 dominoes and L-shaped trominoes (both rotatable). python def tilings(n): dp = [1…