~/problems

Problems

Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.

Trees

Binary trees

Recursive return values (height, best path), BFS by level, BST invariants.

Notes

Recognise it when: you're given a TreeNode. Most answers are a post-order recursion that returns something to the parent.

def height(node):                      # diameter = max over nodes of left + right
    nonlocal best
    if not node: return 0
    l, r = height(node.left), height(node.right)
    best = max(best, l + r)
    return 1 + max(l, r)
  • Level order: BFS processing len(queue) nodes per level.
  • Validate a BST: pass (lo, hi) bounds down. Checking only the immediate children is the classic bug.
  • LCA: if both sides return non-None, this node is the LCA. Otherwise return whichever side isn't None.
  • Serialize: preorder with null markers, and deserialize with an iterator.

Gotchas: deep skewed trees hit the recursion limit, so go iterative or raise it. Tell apart "return value" and "global best".

24 problems

Interview roadmap

Trees Traversals, BSTs, and answers built bottom-up.

Binary trees guide

esc