Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Remove the k-th node from the end of a list in one pass.

Problem: Remove the k-th node from the end of a list in one pass.
class Node:
    def __init__(self, v, nxt=None):
        self.v, self.next = v, nxt
def build(xs):
    head = None
    for x in reversed(xs):
        head = Node(x, head)
    return head
def show(h):
    out = []
    while h:
        out.append(h.v); h = h.next
    return out
def remove_kth(h, k):
    dummy = Node(0, h)
    fast = slow = dummy
    for _ in range(k + 1):
        fast = fast.next
    while fast:
        fast, slow = fast.next, slow.next
    slow.next = slow.next.next
    return dummy.next
print(show(remove_kth(build([10, 20, 30, 40, 50]), 2)), show(remove_kth(build([7]), 1)))
What is printed?
  1. A. [10, 20, 40, 50] []
  2. B. [10, 20, 30, 50] [7]
  3. C. [10, 20, 30, 40] []
  4. D. [10, 20, 30, 50] []

Correct answer: D. [10, 20, 30, 50] []

fast starts k + 1 nodes ahead of slow (from a dummy), so when fast falls off the end, slow sits just before the node to delete. 2nd from the end of 10..50 is 40. The dummy head handles deleting the only node, which returns an empty list instead of crashing. O(n).

More Coding Interview Problems questions

Exams that ask this topic