Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft

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?

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?
def remove_nth(h, n):
    d = N(0, h); fast = slow = d
    for _ in range(n + 1): fast = fast.nx
    while fast: fast, slow = fast.nx, slow.nx
    slow.nx = slow.nx.nx
    return d.nx
print(vals(remove_nth(build([86, 68, 13, 45, 70, 55, 54]), 4)))
  1. A. [86, 68, 13, 70, 55, 54]
  2. B. [86, 68, 45, 70, 55, 54]
  3. C. [86, 68, 13, 45, 55, 54]
  4. D. [68, 86, 13, 70, 55, 54]

Correct answer: A. [86, 68, 13, 70, 55, 54]

fast starts n + 1 steps ahead of slow (both from the dummy), so when fast falls off the end, slow is just before the node to delete; the dummy also handles deleting the head. Output: [86, 68, 13, 70, 55, 54].

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

Exams that ask this topic