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([18, 95, 21, 69, 42, 97, 27, 50, 45])
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. 45 45 8
- B. 45 95 8
- C. 95 45 8
- D. 45 95 9
Correct answer: B. 45 95 8
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: 45 95 8.
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
- Z-array: z[i] is the length of the longest common prefix of s and s[i:], with z[0] defined as 0. What is printed? python s = "abaabaaba" z…
- Kadane's algorithm is applied to an array whose elements are ALL negative, using the version cur = max(x, cur + x), best = max(best, cur)…
- Remove the n-th node from the END of a linked list in one pass, using a dummy node and a gap of n between two pointers. What is printed?…
- Z-array: z[i] is the length of the longest common prefix of s and s[i:], with z[0] defined as 0. What is printed? python s = "bbaaaabab" z…
- Asteroids move along a line: positive values move right, negative move left; on collision the smaller (by absolute value) explodes, equal…
- A difference array is used for q range-increment updates followed by one final read of all n values. What is the total time?