Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Partition a linked list so that all nodes with values < x come before nodes ≥ x, preserving relative order within each part.

Problem: Partition a linked list so that all nodes with values < x come before nodes ≥ x, preserving relative order within each part.
class N:
    def __init__(s, v, nx=None): s.v, s.nx = v, nx
def part(h, x):
    a = A = N(0); b = B = N(0)
    while h:
        if h.v < x: a.nx = h; a = h
        else: b.nx = h; b = h
        h = h.nx
    b.nx = None; a.nx = B.nx
    return A.nx
h = None
for v in reversed([5, 1, 9, 2, 3, 7, 0]): h = N(v, h)
h = part(h, 4); out = []
while h: out.append(h.v); h = h.nx
print(out)
What is printed?
  1. A. [0, 1, 2, 3, 5, 7, 9]
  2. B. [1, 2, 3, 0, 9, 5, 7]
  3. C. [3, 2, 1, 0, 5, 9, 7]
  4. D. [1, 2, 3, 0, 5, 9, 7]

Correct answer: D. [1, 2, 3, 0, 5, 9, 7]

Two dummy-headed lists collect the < 4 nodes (1, 2, 3, 0) and the ≥ 4 nodes (5, 9, 7) in their original order, then are joined. Setting b.nx = None is essential, or the old link from 7 to 0 would create a cycle.

More Coding Interview Problems questions

Exams that ask this topic