</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Search and Validate

What is this?

These problems ask you to find a value in a BST or check that a tree is a valid BST at all. The trick is that you never wander the whole tree โ€” at each node you compare, then step left or right, throwing away the side that cannot hold your answer. It is the same "higher or lower?" guessing game that makes searching feel almost instant.

flowchart TD A["Start at root"] --> B["Compare value to node"] B --> C["Target smaller go left"] B --> D["Target larger go right"] C --> E["Found it or prune the rest"] D --> E

๐Ÿ’ก Fun fact: The most common BST validation bug is checking each node only against its direct children. A node can look fine next to its parent yet still break the order rule against a far-away ancestor โ€” so you must pass down a running low-high window.

๐Ÿ”“ The 4 problems in this chapter are free. Sign in with Google or Microsoft to start solving.


Core idea: A binary search tree stores a global ordering locally โ€” everything in the left subtree is smaller, everything in the right subtree is larger. That single invariant lets you make a decision at each node and discard the half you don't need, turning a tree walk into a directed descent. Every problem here is the same move dressed differently: compare against the node, then commit to one side (or prune it entirely).


The pattern

The BST invariant means each node splits the remaining keys into a smaller-left and larger-right block. So instead of exploring the whole tree, you branch on a comparison: too big means go left, too small means go right. That is an O(h) descent โ€” O(log n) on a balanced tree, O(n) in the worst case when it degenerates into a chain.

Two views of the same invariant power this chapter. The bounds view carries a (low, high) window down each path and asks whether every node stays inside it. The inorder view observes that visiting left, then node, then right yields the keys in strictly increasing order. Whenever you need to validate, prune, or step toward a target, reach for one of these two lenses.


The problems

  • Validate Binary Search Tree โ€” the definitional check. Either confirm the inorder walk is strictly sorted, or push a (low, high) bounds window down each path and verify every node fits. The trap is checking only a node against its immediate children instead of against the inherited window.
  • Closest Binary Search Tree Value โ€” walk toward the target: at each node compare to the target, track the best-so-far, and descend left or right. The ordering guarantees the closest value lies along the single root-to-leaf path you take.
  • Range Sum of BST โ€” sum the keys inside [low, high] while pruning by bounds: if the node is below low, skip its left subtree entirely; if above high, skip its right. The invariant tells you whole subtrees cannot contribute.
  • First Bad Version โ€” note this is binary search on a monotonic predicate, not a true BST. There is no tree; you bisect a sorted version range where "bad" flips from false to true exactly once. It lives here because it shares the same halve-and-commit instinct.

Key takeaways

  • The invariant is the algorithm: smaller-left, larger-right lets you discard half the keys at every step.
  • Two lenses cover everything here โ€” a (low, high) bounds window, or the strictly increasing inorder sequence.
  • Validate against the inherited window, not just the immediate children โ€” the classic BST validation bug.
  • Prune whole subtrees when an entire range falls outside your target interval.
  • First Bad Version is binary search, not a BST โ€” same halving instinct, no tree involved.
  • Cost is O(h): O(log n) when balanced, O(n) when the tree degenerates into a chain.

Order: Validate Binary Search Tree โ†’ Closest Binary Search Tree Value โ†’ Range Sum of BST โ†’ First Bad Version.

Validate Binary Search Tree

Core idea: Every node lives inside a (low, high) window inherited from its ancestors โ€” validating a BST means checking that no node ever escapes its window. Equivalently: an inorder walk of a valid BST is strictly increasing.


Problem, rephrased

Imagine you maintain a filing cabinet for support tickets, organized by ticket ID. The cabinet is a binary tree: from any folder, everything filed to the left has a smaller ID, everything to the right has a larger ID. New interns have been filing tickets, and you suspect someone misfiled one. You need a single sweep that answers: is the entire cabinet still correctly sorted?

A tree is a valid BST when, for every node:

  • all keys in its left subtree are strictly less than the node's key, and
  • all keys in its right subtree are strictly greater than the node's key.

"Strictly" matters: no duplicates allowed. Note this must hold for the whole subtree, not just the two immediate children โ€” that distinction is the entire problem.

Input (tree, by level) Valid BST? Why
[2, 1, 3] True 1 < 2 < 3
[5, 1, 4, null, null, 3, 6] False 4 sits right of 5 but is smaller
[10, 5, 15, null, null, 6, 20] False 6 is right of 10 but 6 < 10
[] (empty) True nothing to violate
[1, 1] False duplicate key

Sign in to continue reading

The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.

Sign in to read the full lesson

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.