Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

What is printed? (finding the k-th node from the end with two pointers)

What is printed? (finding the k-th node from the end with two pointers)
vals = [11, 22, 33, 44, 55, 66]
def kth_end(k):
    lead = trail = 0
    for _ in range(k):
        if lead == len(vals): return None
        lead += 1
    while lead < len(vals): lead += 1; trail += 1
    return vals[trail]
print(kth_end(1), kth_end(4), kth_end(6), kth_end(7))
  1. A. 66 44 11 None
  2. B. 66 33 11 None
  3. C. 55 33 11 None
  4. D. 66 33 11 66

Correct answer: B. 66 33 11 None

Advance the leader k steps, then move both until the leader falls off; the trailer is then k from the end. k = 4 → 33; k = 6 → the first element; k = 7 exceeds the length → None. One pass, O(n).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic