Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Exactly two keys of a BST were swapped by mistake. Find them with an inorder traversal: the first key is the left side of the first descent, the second is the right side of the last descent. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
Problem: Exactly two keys of a BST were swapped by mistake. Find them with an inorder traversal: the first key is the left side of the first descent, the second is the right side of the last descent. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
from collections import deque
class T:
def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs): # level order, None = missing child
root = T(xs[0]); q = deque([root]); i = 1
while i < len(xs):
node = q.popleft()
for side in ("l", "r"):
if i < len(xs) and xs[i] is not None:
setattr(node, side, T(xs[i])); q.append(getattr(node, side))
i += 1
return root
def find_swapped(root):
first = second = prev = None
st, cur = [], root
while st or cur:
while cur: st.append(cur); cur = cur.l
cur = st.pop()
if prev and prev.v > cur.v:
if not first: first = prev
second = cur
prev = cur; cur = cur.r
return first.v, second.v
print(find_swapped(build([10, 5, 15, 2, 17, 12, 7])), find_swapped(build([10, 3, 12, 1, 6, 8, 14])))What is printed?- A. (15, 7) (10, 8)
- B. (17, 10) (10, 8)
- C. (17, 7) (10, 8)
- D. (17, 7) (8, 10)
Correct answer: C. (17, 7) (10, 8)
Inorder of the first tree: 2, 5, 17, 10, 12, 15, 7 – descents 17 > 10 and 15 > 7, so the swapped keys are 17 (first descent's left) and 7 (last descent's right). In the second tree the swapped keys are adjacent in inorder (1, 3, 6, 10, 8, 12, 14): one descent, and both come from it. Taking both ends of the first descent (17, 10) is the classic bug. O(n) time, O(h) stack.
More Coding Interview Problems questions
- Problem: Trim a BST so that only keys in [lo, hi] remain (keeping BST structure), then print its preorder. Trees are built from a…
- Problem: Rebuild a BST from its preorder in O(n) using an upper bound per recursive call, then print its postorder and height (nodes on…
- Problem: Print the top view of a tree (the first node seen in each vertical column, left to right; root column 0, left child −1, right…
- Problem: Return the k-th permutation (1-based, lexicographic) of 1..n directly using the factorial number system. python from math import…
- Problem: Count permutations p of 1..n where for every position i (1-based) p[i] is divisible by i or i is divisible by p[i] (backtracking…
- Problem: Can all matchsticks form a square (every stick used exactly once)? Backtrack placing sticks (longest first) into 4 sides…