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?
  1. A. (15, 7) (10, 8)
  2. B. (17, 10) (10, 8)
  3. C. (17, 7) (10, 8)
  4. 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

Exams that ask this topic