Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: From a sorted linked list, delete EVERY value that appears more than once (keep only distinct values).
Problem: From a sorted linked list, delete EVERY value that appears more than once (keep only distinct values).
class N:
def __init__(s, v, nx=None): s.v, s.nx = v, nx
def dedup(h):
dummy = N(0, h); prev = dummy
while h:
if h.nx and h.nx.v == h.v:
while h.nx and h.nx.v == h.v: h = h.nx
prev.nx = h.nx
else: prev = prev.nx
h = h.nx
return dummy.nx
h = None
for v in reversed([1, 1, 2, 3, 3, 3, 4, 5, 5]): h = N(v, h)
h = dedup(h); out = []
while h: out.append(h.v); h = h.nx
print(out)What is printed?- A. [1, 2, 3, 4, 5]
- B. [2, 4]
- C. [2, 3, 4]
- D. [1, 2, 4, 5]
Correct answer: B. [2, 4]
Unlike plain de-duplication, every copy of a repeated value is removed: 1, 3 and 5 all appear more than once, leaving [2, 4]. The dummy head handles the case where the first value is a duplicate.
More Coding Interview Problems questions
- 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)…
- Problem: Ackermann's function grows faster than any primitive-recursive function. Compute A(2, 3) and count the recursive calls. python…