Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Reorder a linked list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place (find middle, reverse second half, merge).
Problem: Reorder a linked list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place (find middle, reverse second half, merge).
class N:
def __init__(s, v, nx=None): s.v, s.nx = v, nx
def reorder(h):
slow = fast = h
while fast.nx and fast.nx.nx: slow = slow.nx; fast = fast.nx.nx
prev, cur = None, slow.nx; slow.nx = None
while cur: cur.nx, prev, cur = prev, cur, cur.nx
a, b = h, prev
while b: a.nx, b.nx, a, b = b, a.nx, a.nx, b.nx
return h
h = None
for v in [7, 6, 5, 4, 3, 2, 1]: h = N(v, h)
h = reorder(h); out = []
while h: out.append(h.v); h = h.nx
print(out)What is printed?- A. [1, 7, 2, 6, 3, 5]
- B. [1, 2, 3, 4, 7, 6, 5]
- C. [7, 1, 6, 2, 5, 3, 4]
- D. [1, 7, 2, 6, 3, 5, 4]
Correct answer: D. [1, 7, 2, 6, 3, 5, 4]
The middle of 1..7 is 4, so the first half is 1-2-3-4 and the reversed second half is 7-6-5. Interleaving gives 1, 7, 2, 6, 3, 5, 4; with an odd length the middle node ends the list.
More Coding Interview Problems questions
- Problem: From a sorted linked list, delete EVERY value that appears more than once (keep only distinct values). python class N: def…
- Problem: Sum all LEFT leaves of a binary tree (leaves that are the left child of their parent). python class T: def init(s, v): s.v, s.l…
- Problem: List every root-to-leaf path whose values sum to the target. python class T: def init(s, v): s.v, s.l, s.r = v, None, None def…
- Problem: Count the BST keys within [lo, hi], pruning subtrees that cannot contain answers. python class T: def init(s, v): s.v, s.l, s.r =…
- Problem: Delete a node with two children from a BST by replacing it with its inorder successor; print the preorder afterwards. python…
- Problem: Insert keys into an AVL tree (rebalancing with rotations) and print the root and the tree height (a single node has height 1)…