Skip to content
Tech Interview Prep
Technical interview guide

Trees

Hierarchical node structures built on the same pointer discipline as linked lists, traversed via recursion or an explicit stack/queue.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Language-neutral, with ordered-map guarantees cited from the C++ standard containers and java.util as of Java 21.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-3

Explain the tree as a recursive definition and how it changes a production decision.

Answer

The definition

A tree is either empty, or a node plus a finite ordered list of trees. That is the whole definition, and it is also the algorithm: base case = empty, recurse = each child, combine = the node's own contribution with the children's results.

Python
def size(node):
    if node is None:                                # base case
        return 0
    return 1 + size(node.left) + size(node.right)   # recurse + combine

The production decision it forces

The definition says nothing about where the recursion lives. In code it lives on the call stack, and the call stack is a small, fixed, per-thread resource. So the decision is: does the traversal run on the call stack, or on an explicit heap stack you control? That decision is set by the depth of the tree, and for anything parsing client input, the depth is chosen by the attacker.

Concrete case: a service that parses nested JSON from clients. A recursive-descent parser on a 100,000-deep [[[[...]]]] payload does not return an error you can map to a 400. It exhausts the stack.

Numbers, CPython 3.12:

  • sys.getrecursionlimit() defaults to 1000. A recursive walk of a ~1000-node chain raises RecursionError.
  • Raising the limit does not buy safety. Each Python call also consumes a C stack frame, and the OS thread stack is 8 MB by default on Linux (ulimit -s). Past some tens of thousands of frames you get a segfault, not an exception: the process dies with no 500 and no log line.

Iterative version:

Python
def depth_iter(root):
    if root is None:
        return 0
    stack, best = [(root, 1)], 0
    while stack:
        node, d = stack.pop()
        best = max(best, d)
        if node.left:  stack.append((node.left, d + 1))
        if node.right: stack.append((node.right, d + 1))
    return best

Trace on a 1000-node right-leaning chain: the recursive version makes 1000 nested calls and dies at the limit. The iterative version pops one tuple and pushes one child, so the stack never holds more than 1 entry: it returns 1000. On a balanced tree of n nodes the explicit stack peaks at O(height) = O(log n) entries.

RecursiveExplicit stack
Depth lives oncall stack, fixed per threadheap
Limitsys.getrecursionlimit() = 1000 (CPython)available memory; you set the cap
FailureRecursionError / StackOverflowError (JVM) / RangeError (V8)MemoryError / OOM kill
Per-node costone frameone tuple allocation per push
Codemirrors the definitionextra bookkeeping

When recursion is still the right call

Bounded, trusted trees: a config AST, a compiler IR, a DOM you built yourself with a known depth cap. Depth ≤ 100, recursion is clearer and cheaper per node because it allocates no tuple per push. The decision flips on one question: can the depth be set by someone who is not you?

Failure modes and detection

  • RecursionError / StackOverflowError / RangeError in logs with a 500s spike → depth exceeded the limit. Alert on the exception name.
  • Segfault or OOM-kill with no application log → you raised the recursion limit, or the iterative version has no cap. This is the one that pages you at 3am.
  • Detection: a load test with a 10,000-deep payload, plus a hard depth cap at the parse boundary, reject at 512 with a 400, so downstream traversals never see a deep tree.

That cap is the real production decision: bound depth once, at the boundary, instead of defending every traversal.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Walk through the three depth-first orders, including where engineers most often get it wrong.

Answer

The 90-second answer. All three orders visit every node exactly once; they differ only in when the node's own work happens relative to its subtrees. Preorder does node, left, right. Inorder does left, node, right. Postorder does left, right, node. The rule that picks between them is dependency: if the node's result needs its children's results, it is postorder; if the children need the node's, it is preorder. Inorder has no standard definition for n-ary trees, and it is the one that yields sorted output on a binary search tree.

OrderNode visitedSuits
Preorderbefore the subtreescopying, serialising, prefix expressions
Inorderbetween themsorted output from a BST
Postorderafter themdeletion, subtree aggregates, heights, postfix evaluation

Trace. Take this tree:

        A
       / \
      B   C
     / \   \
    D   E   F
  • Preorder: A B D E C F
  • Inorder: D B E A C F
  • Postorder: D E B F C A

Inorder is the only one that reads left-to-right along the bottom of the drawing, which is exactly why it sorts a BST.

Code. Iterative inorder, the version that survives a skewed tree:

Python
def inorder(root):
    stack, out, node = [], [], root
    while stack or node:
        while node:              # descend the left spine
            stack.append(node)
            node = node.left
        node = stack.pop()
        out.append(node.val)
        node = node.right        # then the right subtree
    return out

Trace on the tree above: push A, B, D; pop D → [D]; pop B → [D,B], node = E; push E; pop E → [D,B,E]; pop A → [D,B,E,A], node = C; push C; pop C → [D,B,E,A,C], node = F; push F; pop F → [D,B,E,A,C,F]. Matches the trace above.

Where it goes wrong.

  1. Postorder deletion in the wrong order. free(node) before free(node->left) is a use-after-free: the child pointer is read out of freed memory. The order is forced by the dependency, not by style.

  2. Inorder on a non-BST, or on a BST with duplicates. Sorted output is a property of the BST invariant, not of inorder. Insert duplicates on both sides and the traversal is still inorder but no longer sorted.

  3. Recursion depth. A degenerate BST of 10^5 nodes is 10^5 frames; CPython's default recursion limit is 1000, so the recursive version raises RecursionError. The iterative version above uses O(h) heap stack instead of O(h) call frames: same asymptotics, no interpreter limit.

  4. Emitting on pop in iterative postorder. The standard version tracks last_visited and only emits a node when its right child is None or equals last_visited. Drop that check and a node with a right child is emitted before its right subtree: on the tree above, A comes out before C.

  5. Preorder serialisation without null markers. ABDECF does not identify the tree; A B D # # E # # C # F # # does. Two different trees can share a preorder string.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you explain iterative traversal with an explicit stack without using the usual slogan?

Answer

The stack is a to-do list of unfinished work, and the invariant is what it holds: every node on it is a subtree you have entered but not finished, ordered so the next pop is the next thing you owe. Recursion keeps that list in the call stack where you can't see it; making it explicit just means you can read it and bound it.

Preorder: visit a node, then owe its children. Push right before left so left comes off first.

Python
stack, out = [root], []
while stack:
    node = stack.pop()
    out.append(node.val)
    if node.right: stack.append(node.right)
    if node.left:  stack.append(node.left)

On

      1
     / \
    2   3
   / \
  4   5

stack starts [1]; pop 1 → out [1], push 3, 2 → [3,2]; pop 2 → out [1,2], push 5, 4 → [3,5,4]; pop 4 → [1,2,4]; pop 5 → [1,2,4,5]; pop 3 → [1,2,4,5,3]. Matches recursive preorder.

Inorder: the stack holds the ancestors you are still inside, and you visit a node only once its left subtree is done. So descend left pushing as you go, pop to visit, then switch to the right child.

Python
stack, out, cur = [], [], root
while stack or cur:
    while cur:
        stack.append(cur)
        cur = cur.left
    cur = stack.pop()
    out.append(cur.val)
    cur = cur.right

Same tree: push 1, 2, 4 (cur becomes None); pop 4 → out [4]; pop 2 → [4,2], cur = 5; push 5, pop 5 → [4,2,5]; pop 1 → [4,2,5,1], cur = 3; push 3, pop 3 → [4,2,5,1,3]. Sorted, as inorder of a BST must be.

Postorder: two ways, and the choice is about memory, not taste. Reversed preorder: run the preorder loop pushing left before right, which emits root-right-left, then reverse the output. On the same tree that emits [1,3,2,5,4], reversed [4,5,2,3,1]. It costs O(n) for the output buffer and can't emit a node until the whole traversal finishes. The marker version pushes each node twice (once unvisited, once marked) and emits on the marked pop; the stack stays O(h) and nodes stream out as they finish, at the cost of 2n pushes and pops instead of n. If you're writing into a list anyway, reversed preorder is fewer lines; if a consumer reads nodes as they're produced, take the marker.

Depth is the number that matters. Inorder's stack holds one node per level, so O(h): a balanced tree of 10^6 nodes has h ≈ 20, twenty pointers. A degenerate chain, sorted inserts into a BST, has h = 10^6, so the stack holds a million pointers, 8 MB at 8 bytes each on a 64-bit build. Recursion would hit CPython's default limit of 1000 frames and raise RecursionError long before that. Time is O(n) either way; each node is pushed and popped a constant number of times.

The failure to watch for: writing the inorder loop by analogy with preorder, appending on pop before descending. It visits a node before its left subtree and still looks plausible on a three-node tree. The check is cheap: inorder of a BST must come out non-decreasing, and diffing against the recursive version on random trees catches it in one run.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does breadth-first traversal guarantee, and what does it deliberately leave open?

Answer

Core answer (say this first)

BFS on an unweighted graph guarantees exactly two things. Every reachable node is dequeued once: the visited mark goes on at enqueue time, so nothing enters the queue twice. And nodes leave the queue in non-decreasing order of edge distance from the source, so when a node is dequeued its distance is final and equals the shortest-path length in edges. Reachability plus shortest edge count; that is the guarantee.

Everything else is left open. The order within a level is whatever the adjacency list happens to say: swap two neighbours and you get a different, equally valid BFS. When several shortest paths tie, you get the one discovery order picked, not a canonical one. And BFS says nothing about memory: the frontier can be as wide as the graph.

Why the guarantee holds

The queue is FIFO and each node is enqueued once. Inductively, at the start of a round the queue holds exactly the nodes at distance d; processing them enqueues only undiscovered neighbours, all at distance d+1. So the next round's queue holds exactly distance d+1. That invariant is why snapshotting len(q) before the inner loop separates levels without storing depth on the nodes.

Python
from collections import deque

def levels(adj, src):
    dist = {src: 0}
    q = deque([src])
    out = []
    while q:
        level = []
        for _ in range(len(q)):        # snapshot: fixes the level boundary
            u = q.popleft()
            level.append(u)
            for v in adj[u]:
                if v not in dist:      # mark on enqueue, not on dequeue
                    dist[v] = dist[u] + 1
                    q.append(v)
        out.append(level)
    return out, dist

Trace on adj = {0:[1,2], 1:[0,3], 2:[0,3], 3:[1,2,4], 4:[3]}, src=0:

roundqueue at round startdequeuednewly enqueuedout
0[0]01, 2[[0]]
1[1, 2]1, 23[[0],[1,2]]
2[3]34[[0],[1,2],[3]]
3[4]4—[[0],[1,2],[3],[4]]

dist = {0:0, 1:1, 2:1, 3:2, 4:3}. Time is O(V+E); the frontier is O(V) worst case.

What it leaves open, concretely

  • Within-level order: driven by adjacency-list order, so it is not reproducible across implementations.
  • Tie-breaking: BFS returns a shortest path, not the shortest path. If you need a specific one, you need a tie-break rule.
  • Memory: on a graph with branching factor b and depth d the frontier is O(b^d), against O(bd) for DFS. BFS is the wrong tool when you only need reachability on a wide graph.
  • Weighted edges: the distance guarantee is edge count only. One weight of 5 breaks it; use Dijkstra, or 0-1 BFS with a deque when weights are 0 or 1.
  • Goal checking: checking at enqueue instead of dequeue returns the same distance with less work, but that is a choice BFS does not make for you.

Failure modes

Marking visited on dequeue instead of enqueue: distances stay correct, so tests pass, but a node can be enqueued once per already-dequeued neighbour. On a complete graph K_n that is O(n²) enqueues instead of O(n). Detect it by asserting the queue never exceeds V, or by counting enqueues against V.

Using a stack instead of a queue: you get depth-first order that still looks like a traversal. Detect it with a one-line invariant: assert the dist values of dequeued nodes are non-decreasing.

Omitting the visited set on a cyclic graph: infinite loop, not a wrong answer.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How would you reason about height and depth in a system you own?

Answer

In a system I own, height and depth are two different operational quantities, and the first thing I do is decide which one is bounded by construction and which is data-dependent.

Depth is distance from an entry point downward: call-stack frames, JSON nesting, trace span depth, dependency depth in a build graph. It is known on the way down, so it is a parameter you pass and a limit you set. Height is distance from a node up to its deepest leaf: B+tree height, subtree height. It is known on the way up, so it is a value you return, and it is a property of the data rather than of your code.

The deciding question: can I bound it at design time, or must I measure it?

Bounded by construction: InnoDB. Default page size is 16 KiB (innodb_page_size). A non-leaf page holds roughly 1,200 entries for an 8-byte key plus a 6-byte child pointer, so fanout is about 1,200. Height 3 covers ~1.7 billion rows (1200³); height 4 covers ~2 trillion. A point lookup costs one page read per level, so 3-4 reads, and the upper levels stay in the buffer pool. That is a guarantee I can put in a design doc: index height is fixed by page size and key width, not by row count.

Data-dependent: recursion and parsing. Python's sys.getrecursionlimit() defaults to 1000; CPython 3.12 raises RecursionError instead of segfaulting when the C stack runs out. Jackson 2.15+ caps JSON nesting at 1000 by default via StreamReadConstraints. Go goroutine stacks start at 8 KiB and grow to maxstacksize, 1 GiB by default. None of these are guarantees about your data; they are limits you impose.

Carrying both in one pass:

Python
def walk(node, depth=0, seen=None):
    if seen is None:
        seen = {"max_depth": 0}
    if node is None:
        return -1                      # height of an absent subtree
    seen["max_depth"] = max(seen["max_depth"], depth)
    h = 1 + max(walk(node.left, depth + 1, seen),
                walk(node.right, depth + 1, seen))
    return h                           # height, known on the way up

Trace on A(B(D), C): walk(A,0) sets max_depth=0; walk(B,1) sets 1; walk(D,2) sets 2 and returns 1+max(-1,-1)=0; walk(B,1) returns 1+max(0,-1)=1; walk(C,1) returns 1+max(-1,-1)=0; walk(A,0) returns 1+max(1,0)=2. Final max_depth=2, height=2. Depth is passed down, height is returned up, one traversal.

Failure modes. Unbounded recursion on user input: RecursionError or StackOverflowError, detected by capping depth and returning 400 rather than 500. Deep JSON: parser CPU and memory blow up before you see the payload; the nesting cap is the mitigation, and you alert when it is hit. Deep dependency graph: build time grows with the longest path, so you measure it and fail the build above a threshold.

Alternatives. Recursive with the host stack versus an explicit stack you own: the iterative version trades stack-overflow risk for heap you must bound. Pass depth down versus return height up: you usually need both, so carry depth as a parameter and return height. Bound by construction versus measure and cap.

I pick by asking whether the structure's height is fixed by design. If it is, cite it as a guarantee. If it is not, instrument max depth, set a hard cap, and alert as you approach it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Describe the binary search tree invariant and the evidence you would collect before relying on it.

Answer

The invariant

Every key in a node's left subtree is less than the node's key, and every key in its right subtree is greater. The quantifier is the whole subtree, not the two children: that distinction is the entire question.

Evidence before relying on it

Two separate things have to hold, and they need different evidence.

The construction path enforces it. If you own the insert and delete code, the invariant is a property of that code, and the evidence is a test that exercises it. Property-based fuzzing is the right shape: generate random insert/delete sequences, mirror them into a sorted list, and assert the tree's in-order traversal equals the list. That catches the delete cases (two-child removal, rebalancing) that hand-written tests miss.

The instance actually satisfies it. If the tree arrives from outside your code (deserialized, built by a library, handed over by another team) you cannot assume the construction path. Validate the instance once at the boundary.

Validating an instance

The check carries a permitted open interval down the recursion, narrowing it at each step:

Python
def valid(node, low=float("-inf"), high=float("inf")):
    if node is None:
        return True
    if not low < node.val < high:
        return False
    return valid(node.left, low, node.val) and valid(node.right, node.val, high)

Trace it on a tree where every parent-child pair looks fine:

      5
     / \
    1   6
       / \
      4   7

valid(5, -inf, inf) → 5 in range → recurse left valid(1, -inf, 5) → 1 in range, both children None → True. Recurse right valid(6, 5, inf) → 6 in range → recurse left valid(4, 5, 6) → 4 > 5 is false → False. The whole call returns False. A check that only compares each node to its two children accepts this tree: 1 < 5 < 6 and 4 < 6 < 7 all hold.

Alternatives and when to pick them

ApproachCostCatchesBlind spot
Range check, recursiveO(n) time, O(h) stackdeep violationsCPython's default recursion limit of 1000: a degenerate 10k-node tree raises RecursionError
In-order traversal, assert strictly increasingO(n) time, O(h) stacksame violationsneeds an explicit prev; duplicates need a stated policy
Iterative range stackO(n) time, O(h) heapsamemore code, no stack limit
Fuzz vs sorted referenceO(n log n) per runinsert/delete bugsonly the sequences you generate

Deciding criteria: untrusted input → one-time range check at the boundary, iterative if the tree may be deep. Code you own → fuzz in CI, skip the runtime check. A live structure mutated concurrently → neither traversal is safe; instrument the mutation path instead.

Failure modes

  • Child-only comparison. Accepts the tree above. Detected by the range check, not by spot-checking parents.
  • Recursion depth. A tree built from sorted input is a linked list of height n; the recursive check dies before it answers. Detected by the RecursionError, fixed by the iterative form.
  • Duplicate policy unstated. low < val < high rejects equal keys; if your insert allows duplicates on one side, the check must match that side or it reports false violations.
  • Invariant mistaken for balance. The BST property alone gives O(h) search, and h is n for sorted inserts. O(log n) needs a separate balance invariant (AVL, red-black): validating the BST property tells you nothing about height.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach deletion with two children to an engineer who has only seen it as a rule of thumb.

Answer

Core answer. A node with two children can't be removed in place without breaking the ordering invariant, because both subtrees must stay on the correct side of whatever value ends up there. The fix is to replace the node's key with the key adjacent to it in sorted order: the inorder successor (leftmost node of the right subtree) or the inorder predecessor (rightmost node of the left subtree), then delete that node from the subtree it came from. The successor has no left child by construction, so it has at most one child and splices out in O(h). Nothing else about the tree changes.

State your assumptions before you code: keys unique, tree unbalanced (so h is the height, not log n), nodes identified by position rather than by key.

Mechanism.

Python
def delete(node, key):
    if node is None:
        return None
    if key < node.val:
        node.left = delete(node.left, key)
    elif key > node.val:
        node.right = delete(node.right, key)
    else:
        if node.left is None:
            return node.right          # 0 or 1 child
        if node.right is None:
            return node.left
        succ = node.right
        while succ.left is not None:   # leftmost of right subtree
            succ = succ.left
        node.val = succ.val            # copy key up
        node.right = delete(node.right, succ.val)
    return node

Trace on:

        50
       /  \
      30   70
     / \   / \
    20 40 60 80
            \
            65

delete(root, 50): both children present. succ walks 70 → 60 and stops (60.left is None). node.val = 60. Recurse delete(70, 60): 60 < 70, so delete(60, 60) → 60 has no left child, returns 60.right = 65, so 70.left = 65. Result:

        60
       /  \
      30   70
     / \   / \
    20 40 65 80

Cost: O(h). The walk to the successor plus the recursive delete, both bounded by the height. O(log n) expected for random insertions, O(n) worst case, O(log n) guaranteed in AVL or red-black trees.

Successor vs predecessor. Either preserves the invariant. They differ in what they do to the tree's shape over time. Always taking the successor biases deletions toward the right subtree, and Hibbard's scheme (copy the successor, then delete it) has a known consequence: Culberson and Munro (1989) showed that after Θ(n²) random insert/delete operations the expected height grows to Θ(√n), so search and insert degrade from O(log n) to O(√n). Balanced trees avoid this by rebalancing after the splice: red-black deletion does at most 3 rotations (CLRS), while AVL deletion may rotate at every level up to the root.

Copy vs splice. Copying the successor's key into the target node is the textbook version and is wrong when nodes have identity: any external pointer, iterator, or hash-map entry holding the target node now sees a different key, and any pointer to the successor node is stale. Persistent or immutable trees must splice the node itself: relink the successor's parent to the successor's right child and give the successor the target's children, which is O(1) pointer changes but needs parent pointers or a recursive return.

Failure modes. Duplicate keys break the copy-then-delete step. If duplicates are stored to the right, the leftmost node of the right subtree can hold a key equal to the one being deleted; delete(node.right, succ.val) then matches that equal key higher up in the right subtree and deletes the wrong node, leaving the successor in place and the count wrong. Fix the duplicate convention (e.g. duplicates go right) and delete by node, not by key. The other failure is silent: promoting an arbitrary child instead of the successor leaves a subtree that violates the ordering invariant, and nothing fails until a later search misses a key that is present. A test that checks the invariant over the whole tree after each deletion catches it; a test that only inspects the returned root does not.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does search-tree operations are height-bound matter, and where is it irrelevant?

Answer

The 90-second answer. Every operation that walks a root-to-leaf path (search, insert, delete, predecessor/successor, rank/select, and range scans) costs O(h) in a binary search tree. That bound matters wherever h can grow with n: a mutable tree fed keys in sorted or adversarial order degenerates to a path, and every one of those operations becomes O(n). It is irrelevant in four common situations: the tree is static and balanced by construction; you don't need ordering, so a hash table's O(1) expected lookup makes the height question moot; the data lives on disk, where a B-tree's height is 3–4 for millions of keys and per-level I/O dominates; or n is small enough that a contiguous sorted array beats any pointer-chasing structure.

Where it bites. Inserting ascending keys into a plain BST builds a right spine. Trace it:

Python
class Node:
    def __init__(self, key):
        self.key = key; self.left = None; self.right = None

def insert(root, key):
    if root is None:
        return Node(key)
    cur = root
    while True:
        if key < cur.key:
            if cur.left is None:
                cur.left = Node(key); return root
            cur = cur.left
        else:
            if cur.right is None:
                cur.right = Node(key); return root
            cur = cur.right

root = None
for v in range(1000):
    root = insert(root, v)

insert(0) makes the root. insert(1): 1 < 0 is false, right is None, so Node(1) becomes root.right. insert(2): 2 < 0 false, descend to Node(1); 2 < 1 false, right is None, so Node(2) hangs off Node(1). Every key lands on the right spine; the tree is a linked list of 1000 nodes, height 999 edges. search(999) walks all 1000 nodes.

Arithmetic on the gap: a balanced tree over 1,000,000 keys has height ⌈log2(10^6)⌉ = 20. The same keys inserted in order give height 1,000,000. That is 50,000× more comparisons on the worst lookup, and the code is identical.

Where it doesn't. A static tree built by median-splitting a sorted array has height ⌈log2 n⌉ by construction and never degrades; the bound is a property of the build, not a runtime risk. If you only need membership, a hash table gives O(1) expected and the height bound never enters the picture: you trade away ordering, so range scans and predecessor queries are gone. On disk, a B+tree with fanout 100 over 10^6 keys has height 3 (100^3 = 10^6); the height is so small that the cost is the ~100 µs page read per level, not the comparison count, so "log vs linear" is the wrong axis. And for n in the low hundreds, a sorted array with binary search, or even a linear scan, usually wins, because a contiguous array's cache behavior beats pointer chasing.

StructureLookupOrdered opsWhen it's the right call
Unbalanced BSTO(h), O(n) worstyesstatic, balanced by construction; tiny n
Red-black / AVLO(log n) worstyesmutable ordered map, adversarial input
Hash tableO(1) expectednomembership only, no ordering
B+treeO(log_f n) I/Oyesdata on disk, millions of keys
Sorted arrayO(log n)yes (static)read-only, cache-friendly, small n

Failure modes. The classic overclaim is quoting O(log n) without the balance condition; sorted input is the counterexample, and it survives casual testing because random test data rarely produces a spine. The opposite error is reaching for a balanced tree when a hash table or sorted array is simpler and faster. Detect the first with a height check or an assertion that h ≤ c·log2(n) after bulk load; detect the second by profiling, if you never call a range or predecessor query, the ordering you paid for is dead weight.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do AVL trees and Red-Black trees differ in balancing strictness, rotation overhead on writes, and practical performance profiles?

Answer

AVL trees enforce a strictly balanced invariant: for every node, the height difference between left and right subtrees cannot exceed 1. Red-Black (RB) trees enforce a looser invariant: no two consecutive red nodes on any path from root to leaf, and every path from root to leaf contains the same number of black nodes (the black-height).

Balance Strictness and Theoretical Bound

  • AVL tree: Worst-case height is strictly bounded at $\approx 1.44 \log_2(n)$. For $n = 10^6$, the maximum height is roughly 28.
  • Red-Black tree: The longest path (alternating red and black) can be at most twice the shortest path (all black). Worst-case height is bounded at $2 \log_2(n + 1)$, reaching up to 40 for $n = 10^6$.

Because AVL trees guarantee a smaller maximum height, lookup operations require fewer pointer dereferences and comparisons on average.

Rotation and Rebalancing Mechanics

Both structures perform $O(1)$ rebalancing work locally, but propagate recoloring or height updates up the tree:

PropertyAVL TreeRed-Black Tree
Balance condition$h_{left} - h_{right}
Height bound$\le 1.44 \log_2(n)$$\le 2 \log_2(n + 1)$
Insertion rotationsAt most 1 (single or double)At most 2 (single or double)
Insertion recoloring$O(\log n)$ height recalculations$O(\log n)$ recolorings
Deletion rotationsUp to $O(\log n)$ cascading rotationsAt most 3 rotations
Metadata overheadTypically an integer/short balance factor1 bit per node (red/black, often packed into pointers)

During an AVL deletion, fixing a height imbalance at node $v$ via rotation can decrease the height of $v$'s subtree, which may unbalance $v$'s parent. This can cascade rotations all the way to the root ($O(\log n)$ rotations). In contrast, Red-Black deletion requires at most 3 pointer rotations regardless of tree depth; further adjustments along the ancestral path are pure recolorings without pointer restructuring.

Workload Performance Profiles

  • Read-heavy workloads: AVL trees consistently outperform Red-Black trees. The tighter height bound translates directly to fewer cache misses and branch mispredictions during lookups.
  • Write-heavy workloads: Red-Black trees are preferable. Rotations involve multiple memory writes (updating left/right/parent pointers across 3–5 nodes), which invalidates cache lines and adds pipeline stalls. Red-Black trees cap deletion rotations at a constant upper bound (3), amortizing write cost significantly better.

This explains why production general-purpose libraries choose Red-Black trees (e.g., C++ std::map/std::set in libstdc++, Java's java.util.TreeMap, and the Linux kernel CFS scheduler): general runtimes must guard against high write churn and deep rotation cascades.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How do you validate whether a binary tree is a valid Binary Search Tree (BST) without falling into common traps like only checking local parent-child relations?

Answer

Core answer. A tree is a valid BST iff every node's key lies strictly inside the interval its ancestors define: each left turn from an ancestor A imposes key < A.val, each right turn from an ancestor B imposes key > B.val. Comparing a node only to its immediate children enforces the parent edge and drops every accumulated constraint. Two implementations are standard: propagate (low, high) bounds down a DFS, or check that an in-order traversal is strictly increasing. Both are O(N) time; the DFS costs O(h) stack, the in-order costs O(h) for its explicit stack plus O(1) for the prev pointer.

Why the local check fails.

        10
       /  \
      5    15
          /
         8

Every parent-child edge passes: 5 < 10, 15 > 10, 8 < 15. But 8 sits in the right subtree of 10, so it must exceed 10. The local check never sees that constraint, so it returns True on an invalid tree.

Bounded DFS. None sentinels avoid the INT_MIN/INT_MAX trap entirely.

Python
def is_valid_bst(root):
    def check(node, low, high):
        if node is None:
            return True
        if low is not None and node.val <= low:
            return False
        if high is not None and node.val >= high:
            return False
        return (check(node.left, low, node.val) and
                check(node.right, node.val, high))
    return check(root, None, None)

On the tree above: check(10, None, None) passes; check(5, None, 10) passes; check(15, 10, None) passes; check(8, 10, 15) fails because 8 <= 10. Returns False.

In-order traversal. A valid BST's in-order sequence is strictly ascending, so tracking the previous value is enough.

Python
def is_valid_bst_iter(root):
    stack, curr, prev = [], root, None
    while stack or curr:
        while curr:
            stack.append(curr)
            curr = curr.left
        curr = stack.pop()
        if prev is not None and curr.val <= prev:
            return False
        prev = curr.val
        curr = curr.right
    return True

Trace on the same tree:

Popprev beforeTestResult
5Nonefirst node, no testprev = 5
10510 > 5prev = 10
8108 <= 10return False

Starting prev at None rather than float('-inf') sidesteps the sentinel question. (Python 3 compares int and float exactly, so float('-inf') < node.val is also correct for arbitrary-precision ints, but None is unambiguous.)

Traps.

  • Sentinel values. INT_MIN/INT_MAX bounds reject a tree whose keys equal those limits. Use None or float('-inf')/float('inf').
  • Duplicates. The code above uses strict bounds (<=/>= reject), matching the standard definition. If duplicates are allowed, fix a convention, equal keys go left or right, and relax exactly one bound to match. Mixing the two silently accepts invalid trees.
  • Recursion depth. CPython's default limit is 1000 frames (sys.getrecursionlimit()). A degenerate spine of roughly that many nodes raises RecursionError; the exact count depends on frames already on the stack. Use the iterative version for untrusted input.
  • Morris traversal gives true O(1) extra space by temporarily rewiring right pointers, at the cost of mutating the tree mid-traversal. Worth knowing, rarely worth the complexity.
ApproachTimeExtra space
Bounded DFSO(N)O(h) stack
Iterative in-orderO(N)O(h) stack + O(1)
In-order into arrayO(N)O(N)
Morris in-orderO(N)O(1)

h is tree height: O(log N) balanced, O(N) degenerate. Both correct approaches return False at the first violating node; for debugging, report the node and the bound it broke rather than a bare boolean.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-11

How do you find the Lowest Common Ancestor (LCA) of two nodes in a Binary Search Tree versus a general Binary Tree, and what are their time and space complexities?

Answer

In a Binary Search Tree (BST), key ordering eliminates the need to explore both subtrees. In a general Binary Tree without parent pointers or order invariants, finding the Lowest Common Ancestor (LCA) requires traversing both subtrees to bubble up match indicators.

1. Binary Search Tree LCA

Because keys are strictly ordered (assuming unique keys), we compare the current node value with targets p and q:

  • If both p.val and q.val are strictly less than root.val, the LCA resides in root.left.
  • If both are strictly greater than root.val, the LCA resides in root.right.
  • The split point, where one target is $\le root.val$ and the other is $\ge root.val$, or where root equals either p or q: is the LCA.
Python
def lca_bst(root, p, q):
    curr = root
    while curr:
        if p.val < curr.val and q.val < curr.val:
            curr = curr.left
        elif p.val > curr.val and q.val > curr.val:
            curr = curr.right
        else:
            return curr
    return None
  • Time Complexity: $O(h)$, where $h$ is tree height ($O(\log N)$ balanced, $O(N)$ degenerate skewed tree).
  • Space Complexity: $O(1)$ auxiliary space iteratively (or $O(h)$ call stack if written recursively).

2. General Binary Tree LCA

Without key ordering, a bottom-up post-order traversal checks whether p or q exists in either subtree:

  • Base cases: if root is None or matches p or q, return root.
  • Recurse on root.left and root.right.
  • If both recursive calls return non-null values, p and q were found in separate subtrees, making root their LCA.
  • If only one child branch returns non-null, pass that non-null node upward.
Python
def lca_binary_tree(root, p, q):
    if not root or root is p or root is q:
        return root
    left = lca_binary_tree(root.left, p, q)
    right = lca_binary_tree(root.right, p, q)
    if left and right:
        return root
    return left or right
  • Time Complexity: $O(N)$ worst-case, as every node may need to be visited.
  • Space Complexity: $O(h)$ auxiliary stack frames ($O(N)$ worst-case skewed tree, bound by sys.getrecursionlimit()).

Key Comparison

PropertyBinary Search Tree (BST)General Binary Tree
MechanismValue comparison directs path choice ($p, q$ vs. node.val)Post-order traversal bubbles found references upward
Work per querySingle root-to-LCA path traversedFull tree scan up to $N$ nodes
Time Complexity$O(h)$ ($O(\log N)$ avg / $O(N)$ worst)$O(N)$
Space Complexity$O(1)$ iterative$O(h)$ call stack or explicit stack

Critical Failure Modes and Traps

  1. Assuming both nodes exist: The standard recursive general tree algorithm returns p if p is present but q is not in the tree at all, incorrectly implying p is the LCA. If existence is not guaranteed, a two-pass check or a traversal that counts matching targets is required.
  2. Recursion limit exhaustion: For degenerate trees ($N > 1000$), recursive general tree search raises RecursionError in Python without sys.setrecursionlimit(). An iterative traversal using parent tracking via a hash map requires $O(N)$ space but prevents stack overflow.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How do you solve the Maximum Path Sum problem in a binary tree, and why does a node's return value to its parent differ from the global path sum computed at that node?

Answer

A path in a binary tree cannot branch at more than one node: every node along the path has at most two incident edges. Because a parent can only extend a path upward through one child, a recursive step must distinguish between the maximum path sum passing through the current node as the peak (which may combine both left and right branches) and the maximum gain the node can contribute to its caller (which may choose at most one branch).

The Algorithm and Invariant

We perform a postorder traversal (bottom-up DFS). For each node:

  1. Recursively compute the maximum single-branch gain from the left and right subtrees. Any negative contribution is clamped to 0 (meaning we choose not to extend into that subtree).
  2. Compute the local maximum path sum where this node acts as the highest turning point (the apex): node.val + left_gain + right_gain. Update a global accumulator with this value.
  3. Return to the caller the maximum path sum extending downwards through at most one branch: node.val + max(left_gain, right_gain).
Python
# Python 3.12+ (time: O(N), space: O(H) where H is tree height)
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def max_path_sum(root: TreeNode) -> int:
    max_sum = float('-inf')

    def postorder(node: TreeNode | None) -> int:
        nonlocal max_sum
        if not node:
            return 0

        # Clamp negative sub-paths to 0 (omit them)
        left_gain = max(0, postorder(node.left))
        right_gain = max(0, postorder(node.right))

        # Apex path sum: root + left branch + right branch
        current_path = node.val + left_gain + right_gain
        if current_path > max_sum:
            max_sum = current_path

        # Returnable gain: root + at most one branch
        return node.val + max(left_gain, right_gain)

    postorder(root)
    return int(max_sum)

Worked Trace

Consider this tree containing negative and positive values:

      -10
      /  \
     9    20
         /  \
        15   7
  1. node(15): left=0, right=0. Local apex: 15 + 0 + 0 = 15. Max updated to 15. Return 15 + max(0, 0) = 15.
  2. node(7): left=0, right=0. Local apex: 7. Max unchanged (15). Return 7.
  3. node(20): left_gain = 15, right_gain = 7. Local apex: 20 + 15 + 7 = 42. Max updated to 42. Return value: 20 + max(15, 7) = 35.
  4. node(9): Leaf node. Local apex: 9. Return 9.
  5. node(-10): left_gain = 9, right_gain = 35. Local apex: -10 + 9 + 35 = 34. Max remains 42.

Result is 42 (15 -> 20 -> 7). If node(20) had returned its local apex sum (42) to node(-10), node(-10) would have assembled a invalid branched structure (9 <- -10 -> 20, where 20 simultaneously connects to 15 and 7, which is a fork, not a simple path).

Complexity and Failure Modes

  • Time: $O(N)$ because every node is visited exactly once.
  • Space: $O(H)$ auxiliary call-stack frames. On a degenerate linked-list tree ($H = N$), deep recursion triggers a RecursionError in runtimes like CPython where default sys.getrecursionlimit() is 1000. In production engines processing untrusted or skewed hierarchies, convert this to an explicit postorder traversal using an iterative two-stack or parent-pointer approach.
  • All-negative values: Clamping subtrees to 0 without initializing the global maximum to -∞ (or root.val) leads to returning 0 on trees with only negative nodes (e.g., [-3]), which is incorrect because a valid path must contain at least one node.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How do you serialize and deserialize a binary tree, and how do pre-order traversal with null markers compare to level-order traversal for this purpose?

Answer

The 90-second answer

Both encodings cost the same on the wire, 2N+1 tokens for N nodes, so this is not a compression question. It is a question about the decoder's memory profile and how the consumer wants to read the stream. Pre-order with null markers is the default: one recursive pass, O(H) stack, and the left spine is reconstructible as soon as those tokens arrive. Level-order with null markers is what you reach for when the tree is deep and skewed, because its decoder is iterative and cannot blow the call stack, or when the consumer wants the tree layer by layer. Neither works without the nulls: pre-order alone cannot tell a root with a left child from a root with a right child.

Assumptions: node values are integers that do not contain the delimiter, and a null marker is emitted for every empty child slot.

Why the token count is fixed

A binary tree with N nodes has 2N child slots. N−1 of them are filled by edges, so N+1 are null. Any encoding that records structure explicitly writes N values plus N+1 sentinels = 2N+1 tokens. That is the floor for this family of encodings.

Worked trace

        1
       / \
      2   3
         /
        4

Pre-order DFS emits 1,2,#,#,3,4,#,#,#: 9 tokens. Level-order emits 1,2,3,#,#,4,#,#,#: 9 tokens.

Same length, different order. BFS emits 3 before 4 even though 4 is 3's child; pre-order finishes all of 1's left subtree before it touches 3.

Pre-order code

Python
# Python 3.12
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def serialize_preorder(root: TreeNode | None) -> str:
    out = []
    def dfs(node):
        if node is None:
            out.append("#")
            return
        out.append(str(node.val))
        dfs(node.left)
        dfs(node.right)
    dfs(root)
    return ",".join(out)

def deserialize_preorder(data: str) -> TreeNode | None:
    tokens = iter(data.split(","))
    def dfs():
        val = next(tokens)
        if val == "#":
            return None
        node = TreeNode(int(val))
        node.left = dfs()
        node.right = dfs()
        return node
    return dfs()

Running deserialize_preorder on the trace above: dfs() takes 1, then recurses left and takes 2, whose two children consume # and #; back at 1, the right recursion takes 3, whose left recursion takes 4 (consuming #,#) and whose right recursion consumes the final #. The iterator is exhausted exactly when the tree is complete: no lookahead, no second pass.

Level-order, precisely

Serialize: enqueue the root; loop. Dequeue a node, emit its value, then emit left and right child tokens, enqueuing each child that is not null. Deserialize: parse the first token as the root and enqueue it; then loop. Dequeue a parent, read the next two tokens, attach them as left and right, and enqueue each non-null child. Both directions are single-pass O(N).

Comparison

Pre-order (DFS)Level-order (BFS)
Decoder memoryO(H) stack: O(log N) balanced, O(N) skewedO(W) queue: O(1) skewed, O(N) balanced
Recursion riskYes; a ~1000-node skewed tree raises RecursionErrorNone, purely iterative
StreamingEmits a full root-to-leaf path before the next subtree; left spine renders earlyEmits level by level; nothing at depth d is known until depth d−1 is complete
Wire size2N+1 tokens2N+1 tokens; the last level's trailing nulls can be dropped

Failure modes

  • Delimiter collision. If a value can contain the delimiter, split(",") silently corrupts the stream. Fix with length-prefixed values or a binary format with fixed-width integers.
  • Recursion limit. Python's default sys.getrecursionlimit() is 1000, and serialize_preorder recurses N+1 deep on a right-skewed tree, so a 1000-node chain fails in both directions. Convert to an explicit stack, or switch to BFS.
  • BFS queue blowup. On a complete tree the queue holds up to ⌈N/2⌉ nodes at the last level: for N = 10⁶ that is ~500k deque entries. Pre-order's stack on the same tree is only about 20 frames.
  • Trailing nulls. Both encodings can drop trailing # tokens, but BFS drops an entire final level while pre-order drops only the rightmost leaf's two nulls. Either way the decoder must treat "no more tokens" as null.

Alternatives worth naming

For a BST, pre-order alone suffices: rebuild with min/max bounds and skip the sentinels entirely, halving the payload. For a general tree with distinct keys, pre-order plus in-order needs two passes but no sentinels. Length-prefixed values fix delimiter collision at the cost of a header per token.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

When would you refuse a design because of recursion depth on trees?

Answer

Refuse the design when the tree's height is not bounded by something you control, when the input can be sorted, adversarial, or otherwise shaped so height reaches n. Recursive traversal costs stack depth proportional to height. If height is provably O(log n) and n is bounded, recursion is fine and I keep it. If height can be O(n), the recursion depth is O(n) and the design carries no stack guarantee, so I refuse it and convert to an explicit stack or Morris traversal.

Concretely: a binary search tree built by inserting already-sorted keys is a left spine. Every node's only child is the next. Height equals node count. A recursive inorder over 2,000 such nodes blows CPython's default 1,000-frame limit:

Python
import sys
print(sys.getrecursionlimit())        # 1000 on CPython 3.11

class Node:
    def __init__(self, v, left=None, right=None):
        self.v, self.left, self.right = v, left, right

def inorder(n):
    if n is None:
        return
    inorder(n.left)
    print(n.v)
    inorder(n.right)

root = None
for v in range(2000):
    root = Node(v, left=root)         # left spine, height 2000

inorder(root)   # RecursionError: maximum recursion depth exceeded

Trace: inorder(root) calls inorder(root.left), which calls inorder(root.left.left), and so on. Each call holds its frame until its child returns. By the time the recursion is ~1,000 frames deep (well before the 2,000th node) CPython raises RecursionError. The same code on a balanced 2,000-node tree runs in about 11 frames.

Arithmetic: a CPython frame is on the order of hundreds of bytes. At 1,000 frames that is well under a megabyte of stack, and the default thread stack on Linux is 8 MB, so raising the limit to 10,000 for a 10,000-node spine risks a hard stack overflow (segfault) rather than a catchable exception. That is the second reason to refuse: sys.setrecursionlimit trades a clean error for a crash.

When recursion is fine: height is provably O(log n) (a balanced tree you build and keep balanced, or a heap-shaped array) and n is bounded so depth stays well under the limit. Then the recursive version is shorter and I keep it.

Failure mode to name: random test data never produces the degenerate shape. A random BST of n nodes has expected height O(log n), so tests pass at any size you would try. The failure appears only on sorted or adversarial input: the exact distribution production sees. Detect it by testing on a deliberately degenerate tree (insert 0..n in order) and asserting the height bound in code, not in a comment.

Alternatives, ranked: explicit stack (iterative inorder) (O(h) heap instead of stack, no limit, roughly twice the code; Morris traversal) O(1) extra space, mutates the tree temporarily, easy to get wrong; increase the limit. Only when you have bounded height and measured the frame cost. For a read-only traversal where the tree is already balanced, none of this applies and recursion is the right call.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on inorder traversal of a search tree. How do you evaluate it?

Answer

The position I'd state in the first minute

Inorder is the right primitive only when you need the keys in order, so the design question isn't "is inorder correct" (it is) but where that order comes from and how often you pay for it. My default verdict: a walk per request is fine for static or read-mostly data, or when k is tiny; a full walk per online request on a tree that keeps changing is the thing I push back on.

Assumptions I'd say out loud, because they decide the verdict: is the tree a plain BST, a balanced tree, or a library type (Java TreeMap, C++ std::map) you can't annotate? Is it mutated concurrently? Is k usually much smaller than n, or does the design actually need the whole sorted sequence?

The mechanism, so the claim is checkable

Every key in a node's left subtree is smaller than the node, and every key in its right subtree is larger. Inorder emits left subtree, then node, then right subtree, so by induction each node is emitted after all smaller keys and before all larger ones: the output is sorted. Iteratively, a stack holds the left spine of unvisited nodes. Popping yields the smallest unvisited key because everything to its left has already been emitted; you then descend that node's right subtree's left spine. The stack never exceeds h, the tree height.

Worked trace

Tree built by inserting 5, 3, 7, 1, 4:

        5
       / \
      3   7
     / \
    1   4

Inorder is 1, 3, 4, 5, 7. For k = 3 the answer must be 4.

Python
def kth_smallest(root, k):          # Python 3.11
    stack, node = [], root
    while stack or node:
        while node:                 # descend left spine
            stack.append(node)
            node = node.left
        node = stack.pop()          # smallest unvisited
        k -= 1
        if k == 0:
            return node.val
        node = node.right
    return None

Step by step: node=5, push 5, push 3, push 1, node=None, stack=[5,3,1]. Pop 1, k becomes 2, node = 1.right = None. Pop 3, k becomes 1, node = 3.right = 4. Push 4, node = 4.left = None. Pop 4, k becomes 0, return 4. Three pops, three left-spine descents: O(h + k) node visits, not O(n).

Alternatives, with the numbers that decide between them

ApproachCost for kth of nExtra spaceBreaks when
Inorder walk, early exitO(h + k) visits; n = 10^6, k = 10 gives ~30 visitsO(h) stackk near n, then it is O(n)
Subtree-size augmentation (order-statistic tree)O(log n), ~20 visits at n = 10^6one counter per nodetree is a library type you cannot annotate
Materialise sorted array onceO(n) build, O(1) lookupn keysany write invalidates it
Threaded next-pointersO(1) amortised nexttwo extra pointers per nodeconcurrent mutation of the links

At roughly 100 ns per pointer-chased visit, a full walk of a 10^7-key tree costs about 1 s of CPU per read. That is the number I'd put in front of the teammate: an order-statistic tree answers the same query in ~24 visits at n = 10^7.

Failure modes and how you'd catch them

Walking the whole tree per request is the obvious one, and load tests show it as p99 climbing with data size rather than with request size. A subtler one: a traversal of a mutable balanced tree is not a snapshot. A red-black rotation mid-walk can move a subtree the stack already descended, producing a duplicate key or dropping one. Catch it with a test that walks while a writer inserts and asserts the output is strictly increasing and its length equals the node count. Fixes: hold a read lock (kills write throughput), take a copy-on-write or persistent root so your captured root is a snapshot, or use MVCC versions. And recursion is not free: a recursive inorder on a 10^6-node degenerate chain exceeds Python's default recursion limit of 1000, so the iterative form is load-bearing, not stylistic.

Verdict: approve if the tree is static, or k is small relative to n, or the root is a genuine snapshot. Ask for an order-statistic tree or a cached sorted array if ordered reads are per-request on live data.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

What trade-off does balanced-tree guarantees in libraries force that a junior answer usually skips?

Answer

The guarantee is worst-case O(log n) for get, put, delete and ordered iteration. The trade-off it forces is that you buy that bound with constant factors, memory and cache behaviour, and you give up the O(1) average a hash map gives you. A junior stops at "it's O(log n), use the library." The senior answer is: the library is right, but the log n bound is not why you pick it. You pick it for ordering and range queries, and you accept roughly 40 bytes of node overhead per entry and about log₂(n) cache misses per lookup to get them.

Mechanism

Red-black trees keep height ≤ 2·log₂(n+1) by recolouring and rotating on insert and delete. That bound is what makes the guarantee real, and it is also the cost: every element is a separately allocated node with parent/left/right pointers and a colour bit, so a lookup walks pointers across the heap instead of scanning a contiguous array.

What it costs, concretely

StructureLookupOrdered iterationPer-entry overheadCache misses per lookup
Java TreeMap / C++ std::mapO(log n) worstyes~40 B (JVM, compressed oops) / ~32 B (libstdc++)~log₂ n
HashMap / unordered_mapO(1) avg, O(n) worstnonode + bucket array~1–2
B+tree (DB index)O(log n)yesamortised, packed nodes~2–3 (node fanout)
skiplist (Redis zset)O(log n) expectedyes~1.33 pointers/level avg~log n

At n = 1M, log₂ n ≈ 20, so a std::map lookup can touch ~20 cache lines at ~100 ns each, order 2 µs, where a hash map touches one or two. That gap is the trade-off, and it is invisible in big-O.

Failure modes

Hand-written trees fail on deletion: the rebalancing cases (red-black delete has four fix-up cases) are where implementations break, and the bug surfaces only under specific insert/delete interleavings. Detect it with a property test that checks the red-black invariants after every operation, not with a happy-path unit test.

The guarantee itself has failure modes too: constant factors and cache behaviour mean a tree can be 5–10× slower than a hash map on the same workload, and the per-node overhead can double memory. Detect that with a benchmark (JMH, Google Benchmark) and perf stat cache-miss counters, not by reasoning about big-O.

When the tree earns its cost

When you need ordered iteration, range queries, or predecessor/successor: TreeMap.subMap, std::map::lower_bound. A hash map cannot do those at any constant factor. If you don't need ordering, the guarantee is a cost with no benefit.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

What would you ask a candidate who recites complexity in terms of nodes and height but cannot apply it?

Answer

The question I'd ask

"Here's a std::map<int,int> holding 10^7 keys. A colleague says find() is O(log n), so about 23 comparisons. Another says that if the keys went in sorted order it degrades to O(n). Who's right, and what changes if we swap std::map for a hand-rolled BST?"

That's the whole probe. One question, a forced choice, and it can't be answered by reciting a bound: the candidate has to know which tree they're holding.

What a strong answer sounds like

std::map is a red-black tree. It rebalances on every insert, so the height bound holds whatever order the keys arrive in: h ≤ 2·log2(n+1). At n = 10^7, log2 n ≈ 23.25, so h ≤ ~47 and a lookup costs 23-47 comparisons. The sorted-insertion claim is wrong for std::map and right for the hand-rolled BST.

Then the arithmetic that makes it concrete. The hand-rolled BST fed sorted keys is a linked list: the last insert walks 10^7 nodes. Each step dereferences a node that isn't in cache, order 100 ns, so that single lookup is ~1 s. The balanced case is ~23 dereferences, ~2.3 µs. Five to six orders of magnitude, from identical asymptotic notation.

Follow-ups, and what each one tests

  • "AVL instead of red-black: what changes?" AVL's height bound is tighter, h ≤ 1.44·log2(n+2), so lookups are shallower; the price is more rotations per insert. Red-black trades a looser bound for cheaper updates. A candidate who can't say which way the trade runs is still reciting.
  • "Read-mostly index of 10^6 keys: std::map or a sorted std::vector?" Sorted vector: binary search is ~20 probes, all in contiguous memory, so the cache does the work. std::map pays three pointers plus a colour word, 32 bytes of overhead before the payload on a 64-bit build, and every hop is a potential miss. Rare writes, the vector wins; frequent inserts, the O(n) memmove on insert kills it.

What the reciter does

They answer the first question with "O(log n)" and stop. They don't ask whether the tree is balanced, don't separate the container from the data structure, and don't notice the two colleagues are describing two different trees. The tell is that they never name a tree.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of the Morris traversal?

Answer

Inject a concurrent reader.

Start a second thread that walks the same tree while the Morris traversal runs: a plain recursive inorder, a successor lookup, a serializer, anything that trusts right. Between pred.right = cur and pred.right = null, the tree is not a tree: some node's right pointer aims at an ancestor. A reader that follows it either loops forever or returns a node that is not the successor. That is the failure, and it is silent: no exception, no crash, just a wrong answer or a hung thread.

The window is the whole descent, not one instruction. Threads are created on the way down and cleared on the way back, so for a tree of height h the tree is corrupt for most of the walk.

Concrete harness, Java 21:

Java
static void morris(Node root, Consumer<Node> visit) {
    Node cur = root;
    while (cur != null) {
        if (cur.left == null) { visit.accept(cur); cur = cur.right; }
        else {
            Node pred = cur.left;
            while (pred.right != null && pred.right != cur) pred = pred.right;
            if (pred.right == null) { pred.right = cur; cur = cur.left; }    // thread
            else { pred.right = null; visit.accept(cur); cur = cur.right; }  // unthread
        }
    }
}

static void inorder(Node n, List<Integer> out) {   // the reader
    if (n == null) return;
    inorder(n.left, out);
    out.add(n.key);
    inorder(n.right, out);
}

Trace it on root 2 with children 1 and 3. Morris sets 1.right = 2 while descending, then visits 1, then unthreads at 2. If the reader runs inorder(2) inside that window: it descends to 1, adds 1, follows 1.right to 2, descends 2.left back to 1, adds 1 again, follows 1.right to 2. Forever, until the stack overflows. The reader never terminates, and its output is wrong even before it dies.

Second injection: throw inside visit. Morris restores the tree on the way back up, so an abort mid-walk leaves threads behind permanently. Throw when visiting the leftmost node, at that moment 1.right still points at 2, and every later inorder walk of that tree loops. This catches the team that believes "it restores the structure afterwards" is unconditional; it is conditional on the walk completing.

What a team that understands it says: the mutation is not a bug to lock around, it is a design constraint. Either the tree has a single writer and readers are excluded for the duration, or Morris is the wrong tool. The fix is a decision, not a mutex: a lock around the traversal serialises exactly the readers you were trying to keep concurrent.

Where it is actually worth it: a skewed tree of 10^6 nodes. Iterative inorder with an explicit stack holds up to 10^6 node references, roughly 4–8 MB on a 64-bit JVM, and that is the case Morris wins. On a balanced tree of the same size the stack is about 20 frames and Morris buys nothing while costing you the mutation window. So the injection is worth running only if the team's tree can be deep and single-writer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How does the complete-tree array layout interact with rollback, and where do people ignore that?

Answer

Take "rollback" as reverting a sequence of mutations to an earlier state: a transaction abort, an undo log, or a snapshot restore. The array layout interacts with it through one property: position is identity. A node has no address of its own; it is whatever sits at index i. That gives rollback exactly two shapes, and each is cheap or expensive in a way a pointer tree is not.

Snapshot rollback is a memcpy. snap = a.copy() then a[:] = snap restores the whole heap in O(n) with no pointer fixups, no reference counting, no deep copy. A pointer tree needs a deep copy (O(n) allocations) or a persistent structure. This is the array layout's genuine rollback advantage, and it is why array-backed heaps serialize cleanly.

Incremental rollback is an undo log of index pairs. Sift-up and sift-down only swap, so record each swap and replay it backwards.

Python
class RollbackHeap:
    def __init__(self):
        self.a = []
        self.undo = []

    def push(self, x):
        self.undo.append(None)              # operation boundary
        self.a.append(x)
        i = len(self.a) - 1
        while i > 0:
            p = (i - 1) // 2
            if self.a[p] <= self.a[i]:
                break
            self.undo.append((p, i))        # record the swap
            self.a[p], self.a[i] = self.a[i], self.a[p]
            i = p

    def rollback(self):
        while self.undo and self.undo[-1] is not None:
            p, i = self.undo.pop()
            self.a[p], self.a[i] = self.a[i], self.a[p]
        if self.undo:
            self.undo.pop()                 # boundary
            self.a.pop()                    # the appended element

Trace push(5), push(3), push(4), then two rollback() calls:

  • push(5): undo=[None], a=[5]. i=0, loop skipped.
  • push(3): undo=[None,None], a=[5,3]. i=1, p=0, a[0]=5 > a[1]=3 → record (0,1), swap → a=[3,5], i=0. undo=[None,None,(0,1)].
  • push(4): undo=[None,None,(0,1),None], a=[3,5,4]. i=2, p=0, a[0]=3 <= a[2]=4 → break.
  • rollback(): top is None, while-loop skipped; pop None; a.pop() → a=[3,5]. undo=[None,None,(0,1)].
  • rollback(): top is (0,1) → swap → a=[5,3]; pop None; a.pop() → a=[5]. undo=[None].

Final a=[5]. Each rollback is O(log n) entries, not O(n).

Where people ignore the interaction:

  1. The snapshot is shallow. a.copy() copies references. If the heap holds mutable records, rollback restores the shape and leaves the payloads mutated: the invariant holds, the data is wrong. Detect it by checksumming payloads after rollback, not just the array.
  2. Index handles diverge. Any external map keyed by index (key → position, for decrease-key) is invalidated by every swap and by any rollback that doesn't also rewind the map. Pointer trees have stable node identity; array indices are positional. Assert map[i] == i after rollback.
  3. Snapshot cost is per transaction, not per operation. A 10^6-element array of 8-byte values is 8 MB; snapshotting per transaction at 10^4 transactions/s is 80 GB/s of memcpy (hypothetical figures). The undo log is O(log n) entries per push instead.
  4. Partial failure. If the comparator raises mid-sift, the array is left in a non-heap state. Rollback must replay the swaps, not merely restore values, or you get a valid-looking array that violates the invariant. Run a heap-invariant check after rollback in tests.
  5. Versioned rollback is O(n) per version. Path copying on a pointer tree creates O(log n) new nodes per version; positional indices cannot share a suffix, so every version copies the array.

Use the array layout when rollback is snapshot-to-one-state and elements are trivially copyable. Use a pointer tree when you need stable node identity, path-copied versions, or rollback that leaves payloads untouched.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How would you review a pull request whose risk is subtree aggregates?

Answer

I'd read the mutation paths first, not the query code. The assumption I'd state up front: the PR adds or changes a subtree aggregate (size, sum, min/max, count) on a balanced BST or segment tree, and the aggregate is stored at each node rather than computed on demand.

The verdict turns on one question: does every path that relinks nodes also recompute the aggregate? If yes, approve with a note on test coverage. If any path misses it, block.

Concretely, I'd grep the diff for every function that assigns to .left, .right, or .parent. That's insert, delete, rotate, rebalance, split, merge, bulk build, deserialize, clone. Rotations are the classic miss:

Python
def rotate_left(x):
    y = x.right
    x.right = y.left
    y.left = x
    # missing: x.size = 1 + size(x.left) + size(x.right)
    #          y.size = 1 + size(y.left) + size(y.right)
    return y

Trace it. Tree with keys 1, 2, 3, sizes correct:

    2 (size 3)
   / \
  1   3

rotate_left(2) without the size updates:

    3 (size 1, stale)
   /
  2 (size 3, stale)
 /
1

Now rank(root, 4): how many keys are smaller than 4. At root 3: 4 > 3, so return size(3.left) + 1 + rank(3.right, 4) = size(2) + 1 + 0 = 3 + 1 = 4. Correct answer is 3. Off by one, and it stays silent until a rotation or deletion fires.

That's why the test I'd ask for is a property test, not a fixture: after every insert, delete, and rebalance, recompute the aggregate from scratch and assert it equals the stored one. A fixture with a fixed insertion order can pass while the deletion path is broken.

The alternatives matter for the review comment:

ApproachUpdateQueryExtra memoryReview risk
Aggregate at each nodeO(h) ≈ 40 writes at n=10^6O(h)1 word/nodeevery mutation path must update
Compute on demandO(1)O(n)0none; query is linear
Secondary index (Fenwick/segment tree)O(log n)O(log n)O(n)two structures must stay in sync

For a red-black tree of 10^6 nodes, h ≤ 2 log2(n+1) ≈ 40, so ~40 node writes per mutation. If the PR computes on demand and the tree is small, I'd approve and note the complexity; if it stores the aggregate, the update discipline is the whole review.

Failure modes I'd name in comments: deletion that removes a node without walking back up; lazy propagation that defers the aggregate past a query; split/merge in a treap that rebuilds one side and forgets the other; deserialization that trusts stored sizes instead of recomputing; concurrent mutation where the aggregate is updated outside the lock. Each is detected by the same property test plus a fuzz run with random op sequences.

So the comment I'd leave: "Every mutation path must recompute size from children after relinking. Add a property test that recomputes from scratch after each op. Blocking until the rotation path is covered."

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the smallest experiment that would change your mind about checking structural properties?

Answer

Assumption first. "Structural properties" here means tree equality: same shape and same values, not just the same multiset of nodes. The belief worth testing is the one most people actually hold: a preorder serialisation is a faithful stand-in for pairwise structural recursion, so I can compare strings and skip the recursion. That belief is falsifiable, and the smallest experiment that kills it uses two trees of two nodes each. One node can't differ structurally, so two is the floor.

The experiment.

Python
class Node:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def same(a, b):                      # pairwise recursion
    if a is None or b is None:
        return a is b
    return a.val == b.val and same(a.left, b.left) and same(a.right, b.right)

def ser(n, out):                     # preorder, no null markers
    if n is None:
        return
    out.append(n.val)
    ser(n.left, out)
    ser(n.right, out)

A = Node(1, left=Node(2))            # 1 -> left 2
B = Node(1, right=Node(2))           # 1 -> right 2

Trace same(A, B): both non-null, 1 == 1. Recurse same(A.left, B.left) = same(Node(2), None). b is None, so it returns a is b → False. same returns False.

Trace ser(A, []): append 1 → [1]; ser(Node(2), out) appends 2 → [1, 2]; that node's children are null, so nothing more; then ser(None, out) does nothing. Result [1, 2]. Trace ser(B, []): append 1 → [1]; ser(None, out) does nothing; ser(Node(2), out) appends 2 → [1, 2]. Result [1, 2].

Both serialise to "1,2". The two checkers disagree on a two-node input.

checkerABverdict
same1→left 21→right 2not equal
ser"1,2""1,2"equal

What changes my mind. If ser had produced different strings, the belief would survive this input and I'd move to the next-smallest adversarial pair: three nodes with a null in the middle. It didn't, so the belief is dead: serialisation without null markers is not a stand-in. Adding null markers fixes it; the strings then diverge at the second token (1,2,… vs 1,null,…), and that's the version I'd ship.

If the belief is about cost, not correctness. Then the smallest experiment is a timing, not a pair of trees: one tree of a fixed size, both checkers, wall-clock over N runs. The number that changes my mind is a ratio, not a boolean, if serialisation isn't at least ~2× faster at the size I actually see, the extra allocation isn't worth the null-marker discipline.

When not to run it. If trees are already canonicalised at the boundary (children sorted, nulls materialised) the structural check is redundant and the experiment is moot. That's a design decision, not a measurement.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you document choosing a tree so the next owner can operate it?

Answer

In the first two minutes

I'd assume the tree is already in the code and the next owner is an on-call engineer who didn't make the choice. The deliverable is a decision record that lives in the repo next to the code, not a wiki page, so it's reviewed in the same pull request and goes stale visibly.

Five fields, and nothing else: the query the tree answers, the invariant it maintains, the operations with their complexity, the operational contract (thread-safety, memory, what to watch), and the exit condition. If a field is missing, the next owner re-derives the decision under incident pressure, which is when they'll get it wrong.

The record itself

# ADR-014: ordered event index
Status: accepted 2024-06-11
Query: all events with ts in [t1, t2), returned in ts order.
Structure: java.util.TreeMap<Instant, Event> (red-black tree).
Rejected: HashMap<Instant, Event> — a range query needs a full O(n)
  scan plus a sort; measured 180 ms vs 2 ms at 1M events.
Invariant: keys unique; comparator is Instant natural order; keys are
  immutable and never mutated after insert.
Operations: put O(log n); subMap(t1, t2) O(log n + k);
  floorKey/ceilingKey O(log n).
Contract: NOT thread-safe. Guard with a lock, or swap to
  ConcurrentSkipListMap if reads dominate writes.
Exit condition: if range queries fall below 5% of traffic, replace
  with a hash map.

The query, in code

Java
// checked against OpenJDK 21
NavigableMap<Instant, Event> index = new TreeMap<>();
index.subMap(t1, true, t2, false); // O(log n + k), already ordered

That one line is the whole justification. A HashMap cannot express it; you'd scan every entry and sort the result.

What the next owner actually needs to operate it

ConcernTreeMapConcurrentSkipListMap
Range queryO(log n + k)O(log n + k)
Point lookupO(log n)O(log n) expected
Thread-safeNoYes
IteratorFail-fast (CME)Weakly consistent
Node overhead~40 B/entry~40 B/entry

The ~40 bytes is a 64-bit HotSpot estimate with compressed oops (12-byte header, five references, a colour byte, padded to 40) before the key and value. Confirm with JOL on your own JVM rather than trusting the number.

Failure modes and how they're detected

Mutating a key after insert breaks the ordering invariant: get() starts returning null for keys that are present. Detect it with a test that walks the map and asserts the comparator is non-decreasing, and by making the key type immutable.

Unsynchronized concurrent put is a data race that corrupts the tree or loses an update. Single-threaded tests pass; a multi-threaded stress test is the only thing that finds it. The record says "NOT thread-safe" in capitals for exactly this reason.

An exit condition nobody monitors is decoration. The 5% range-query threshold has to exist as a dashboard panel (range queries as a fraction of total, tree entry count, and p99 of the subMap call) or the next owner will keep paying O(log n) for a workload that became point lookups.

The part that decides it

Record the rejected alternative and the measurement that killed it. "HashMap, 180 ms vs 2 ms at 1M events" tells the next owner what would have to change for the decision to flip; "we chose a tree because it's ordered" tells them nothing they can act on.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

What belongs in a runbook section on trees versus hash structures, and what does not?

Answer

A runbook section on trees versus hash structures is not a data-structures primer. It earns its place only where the choice produces a symptom an on-call engineer can see and act on. So it should name the structure each hot path actually uses, the symptom that points at it, the check that confirms it, and the fix with its blast radius. It should not carry Big-O tables, definitions, or the design debate that picked the structure: an engineer reading at 3 a.m. cannot act on any of those.

What belongs, and what does not

BelongsDoes not
The concrete type per hot path: TreeMap for the routing table, HashMap for the session cache, a Redis ZSET for the leaderboardWhat a red-black tree or a skiplist is
The symptom: p99 on floorKey/subMap calls, a rehash pause, a ClassCastException out of a comparatorAn O(1) vs O(log n) comparison table
The check: jcmd <pid> GC.class_histogram, Redis SLOWLOG GET, a heap histogram filtered to the map typeThe rationale for choosing the tree
The fix and its blast radius: pre-size the map, swap HashMap for ConcurrentSkipListMap"We might migrate to X later"

The failure modes the section must cover

Hash structures fail in two ways worth an entry. First, rehashing: a single put that crosses the load factor is O(n), so a map growing past its threshold shows up as a latency spike on one unlucky request, not a gradual slope. Java's HashMap defaults to load factor 0.75 and capacity 16, doubling on resize; a 1M-entry map sits at capacity ~2M, and that resize copies every entry. Detect it by correlating the spike with map size on a dashboard, not by reading code. Second, collision flooding: if keys are attacker-controlled and the hash is predictable, an adversary forces every key into one bucket. Java 8+ mitigates this by treeifying a bin at 8 entries once capacity reaches 64, but the general fix is a keyed hash: Rust's HashMap uses SipHash, Python randomizes with PYTHONHASHSEED.

Trees fail differently. A TreeMap comparator inconsistent with equals silently drops entries: compare returning 0 for two unequal keys makes the second overwrite the first, and the map is quietly smaller than the input. Detect it by asserting map.size() against the source count after a load. The other cost is memory and cache behaviour: a TreeMap.Entry is roughly 40 bytes against a HashMap.Node at roughly 32 on a 64-bit JVM with compressed oops, and every lookup chases pointers, so a tree at the same entry count is slower on point reads than the asymptotics suggest.

A worked example

The /events endpoint's p99 goes from 12 ms to 340 ms after a deploy. The runbook says: check whether a range query is running over a hash structure. jcmd <pid> GC.class_histogram | grep HashMap shows 1.2M entries. The code filters map.keySet() for k >= lo && k < hi: a full scan, O(n) per request. The fix is TreeMap.subMap(lo, hi), O(log n + k). The runbook entry is the symptom, the check, and the fix, not the explanation of why a tree is ordered.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

How should on-call treat an alert that names n-ary trees as the cause?

Answer

First two minutes

An alert that names a data structure ("n-ary tree walk slow", "recursive child traversal latency") is reporting where the rule's author believed the problem was. That belief came from somewhere: a stack frame in the payload, a metric label on a code path, or a template written during an earlier incident. Treat it as a hypothesis with a provenance, and spend the first five minutes testing it against the symptom rather than reading traversal code.

  1. Confirm impact from the SLO dashboard, not the alert. If error rate and p99 sit inside budget, the alert is noise: silence it, file a ticket, move on.
  2. Read the payload for the evidence behind the name: stack frames, label values, a trace ID. A name with no frame or label under it is a guess.
  3. Mitigate before diagnosing: roll back the last deploy, flip the flag, shed load. Root-causing a live incident is a luxury you take after the bleeding stops.

What the name usually is

Alert styleWhat it measuresTriage moveFailure mode
Cause-named ("tree walk slow")A code path or labelCheck whether that path's own latency movedChase a stale name while a dependency saturates
Symptom-based (SLO burn rate)User-visible error/latencyPage on budget burn, then find the causePages on impact you can't yet explain

A cause-named alert is only as good as the label it carries. Here's a typical one:

Alert: CatalogRenderLatencyHigh
expr: histogram_quantile(0.99,
        rate(http_request_duration_seconds_bucket{handler="catalog_render"}[5m])) > 0.5
for: 5m
labels: {service="catalog", handler="catalog_render", tree="category"}
annotations:
  summary: "p99 620ms on catalog_render (n-ary category tree walk)"

The expression measures handler latency. tree="category" is a dimension, not a cause. So the first question is whether p99 rose because the tree got deeper or wider, or because something the handler calls got slow. Pull the span breakdown for catalog_render and compare the traversal span against its children. If the traversal span is flat and a downstream span grew, the name is wrong.

Is it page-worthy

With a 99.9% / 30-day SLO the error budget is 0.1% × 30d = 43.2 minutes. A 5-minute window at 1% error rate burns 1% / 0.1% = 10×, i.e. 50 minutes of budget in five: page. A 5-minute window at 0.05% burns 0.5×, i.e. 2.5 minutes: ticket, don't wake anyone.

Failure modes

  • Chasing the name: you profile the traversal, it's fine, and twenty minutes later the connection pool is the story. Detect it by watching the named path's own latency while the handler's rises.
  • Dismissing the name: a change made the tree unbounded, one category with 40k children, and you're debugging infra. Detect it by watching the tree label's cardinality or a depth metric.
  • Stale template: the name was accurate two incidents ago. Detect it by checking whether the alert's own labels still exist in the code.

The deciding criterion is whether the name has evidence attached. Frame or label present, test it first. Absent, treat it as a symptom alert and find the cause yourself.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you brief product on why tree diameter delays a ship date?

Answer

Product doesn't want the algorithm. They want three things: what the delay buys, what it costs, and what happens if we don't pay it. So I lead with the decision and the number, and keep the mechanism to one sentence.

The situation. The critical-path panel shows the longest dependency chain in a customer's build graph, so they can predict worst-case build time. We scoped it as all-pairs longest path: for every node, walk to every other node, keep the max. That's O(n²). On our reference graph (50k nodes) it returns in about 25 seconds: already over the 5-second panel budget, but tolerable in a demo. On the largest customer's graph, 2M nodes, it's 4×10¹² pair operations; at ~10⁸ ops/sec that's roughly 11 hours. The panel doesn't time out, it never returns. (Figures illustrative.)

What the delay buys. The longest path in a tree has a two-pass solution that's O(n): BFS from any node to the farthest node u, then BFS from u to the farthest node v; dist(u,v) is the diameter. Same answer, ~2M node visits, milliseconds. It's about two days to implement and a day to test against the all-pairs result on small graphs.

The options.

OptionShip dateCostRisk
Ship all-pairs as scopedOn timenonePanel unusable above ~100k nodes
Delay ~3 days for O(n) two-pass+3 days3 eng-daysnone known; needs tree-only guard
Ship now, cap graph sizeOn timenoneBiggest customers see "graph too large"

Recommendation. If the customers asking for this panel are the ones with million-node graphs, take the three days: it's the difference between a feature and a demo. If they're not, ship with the cap and schedule the fix behind the next release; the cap is honest and reversible.

What I'd flag to product. The two-pass answer is only correct on a tree. If the dependency graph has cycles or is weighted, the diameter is a different problem and the estimate changes. I'd confirm the graph is acyclic and unweighted before promising the three days, because that's the assumption the whole estimate rests on.

How we'd know it's fixed. Assert the two-pass result equals the all-pairs result on a few hundred random small trees in CI, and add a latency test on a 2M-node fixture that fails if the panel exceeds 5 s. That turns "we think it's fast now" into a number product can hold us to.

Curated: · Written: · Reviewed:

Difficulty: Medium