Data Structures & AlgorithmsVery hardTCS Digital · Infosys SP
Floyd's cycle detection on a list whose last node links back into the list. What does this print (meeting value, cycle-start value, cycle length)?
Floyd's cycle detection on a list whose last node links back into the list. What does this print (meeting value, cycle-start value, cycle length)?
h = build([93, 63, 96, 30, 16, 91, 88, 71, 62, 18])
t = h
while t.nx: t = t.nx
p = h
for _ in range(1): p = p.nx
t.nx = p
s = f = h
while True:
s, f = s.nx, f.nx.nx
if s is f: break
meet = s.v
s = h
while s is not f: s, f = s.nx, f.nx
start = s.v
n, q = 1, s.nx
while q is not s: q, n = q.nx, n + 1
print(meet, start, n)- A. 18 63 9
- B. 18 18 9
- C. 63 18 9
- D. 18 63 10
Correct answer: A. 18 63 9
After the first meeting, moving one pointer back to the head and stepping both one node at a time makes them meet at the cycle's entry (distance-to-start = distance-from-meeting mod cycle length). Output: 18 63 9.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- One Lomuto partition (pivot = LAST element; i marks the end of the 'less than pivot' region; when a[j] < pivot, increment i and swap a[i]…
- 9 people stand in a circle numbered 1 to 9. Counting starts at person 1, and every 3rd person is removed (counting continues from the next…
- A hash-map two-sum returns the first index pair (i, j), i < j, found while scanning left to right. What is printed? python def twosum(a…
- A sorted array was rotated to give [29, 47, 50, 57, 60, 61, 75, 4, 5, 8, 13]. Binary search finds the index of the minimum: while lo < hi…
- Lines of heights [6, 9, 5, 6, 8, 1, 8, 3, 5] stand at x = 0, 1, …, 8. Two pointers find the pair of lines that, with the x-axis, holds the…
- Exponential search: double the bound i (1, 2, 4, …) until a[i] ≥ key or i passes the end, then binary-search the last range. How many…