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?- A. [0, 1, 2, 3, 5, 7, 9]
- B. [1, 2, 3, 0, 9, 5, 7]
- C. [3, 2, 1, 0, 5, 9, 7]
- 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
- List A has a nodes before it joins a shared tail of c nodes; list B has b nodes before the same tail, with a ≠ b. Pointer p walks A and…
- Problem: Move the coins of a binary tree so every node has exactly one coin; a move passes one coin along one edge. Count the minimum…
- Problem: Find the maximum |a − b| where a is an ancestor of b in a binary tree. python class T: def init(s, v): s.v, s.l, s.r = v, None…
- Problem: Return the (1-based) level of a binary tree with the largest sum of values (smallest level on ties). python class T: def init(s…
- Problem: Every minute, fresh oranges (1) next to rotten ones (2) rot (4 directions). How many minutes until no fresh orange remains (−1 if…
- Problem: Find the path from node 0 to node 3 with the maximum product of edge success probabilities (Dijkstra on −log p, or a max-heap on…