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([60, 73, 28, 96, 31, 84, 81, 54])
t = h
while t.nx: t = t.nx
p = h
for _ in range(3): 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. 84 96 5
- B. 84 84 5
- C. 84 96 6
- D. 96 84 5
Correct answer: A. 84 96 5
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: 84 96 5.
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
- What does this loop-counting code print? (Python) python n, c = 70000, 0 i = 2 while i <= n: c += 1 i = i i print(c)
- In the binary array [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0] you may flip at most 2 zeros to ones. What is the length of the longest run…
- Evaluate an infix expression of single digits with two stacks (operands and operators, usual precedence, left-associative). What is…
- Swap every two adjacent nodes of a linked list by relinking (not by swapping values). What is printed? python def swappairs(h): d = p =…
- How many pairs (i < j) of [2, 15, 17, 10, 24, 2, 10, 2, 4, 9] have a[i] + a[j] divisible by 4? (Count remainders mod 4 and pair r with 4 −…
- A 2-D array A[0..11][0..29] of 2-byte elements is stored in column-major order starting at address 2000. What is the address of A[9][6]?