</> 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

Order Statistics and Codec

What is this?

A BST already knows the order of its values, so it can answer position questions โ€” what comes next, how many are smaller โ€” and it can even save itself to a flat list and rebuild perfectly. You lean on the sorted shape instead of storing extra bookkeeping. The order rule alone carries enough information to reconstruct the whole tree.

flowchart TD A["BST encodes a total order"] --> B["Find next-larger value"] A --> C["Count how many are smaller"] A --> D["Save to a list and rebuild"]

๐Ÿ’ก Fun fact: Serializing a general binary tree needs null markers to record its shape, but a BST does not. Just write the values in preorder โ€” the ordering rule alone tells you exactly where each value belongs when you rebuild.

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


Core idea: Because a BST already encodes a total order, it can answer positional and counting questions โ€” what comes next, how many are smaller โ€” and even rebuild itself from a flat list without storing any structure markers. The shared thread is that the ordering invariant is enough information; you never need to record shape explicitly, only the values and the rule that arranges them.


The pattern

These problems lean on the same fact from two directions. The inorder sequence of a BST is sorted, so "the next value" or "how many are smaller" become questions about position in that sequence rather than full traversals. And because the sorted order is recoverable from comparisons alone, a preorder list plus the bounds rule is enough to reconstruct the exact tree โ€” no null markers, no delimiters beyond the values themselves.

So you either navigate the order (successor, rank) in O(h) or O(log n) per query, or you exploit the order to rebuild the whole tree in a single O(n) pass. Either way the win is the same: the invariant carries the structure for you.


The problems

  • Inorder Successor in BST โ€” find the next-largest key in O(h) without a full traversal. If the node has a right subtree, the successor is its leftmost descendant; otherwise it is the lowest ancestor for which the node sits in the left subtree. A single downward walk finds it.
  • Count of Smaller Numbers After Self โ€” for each element, count how many later elements are smaller. Solvable with an order-statistics BST (augment nodes with subtree sizes), a Binary Indexed Tree over compressed values, or merge sort that counts inversions while merging. All three turn the rank query into roughly O(n log n).
  • Serialize and Deserialize BST โ€” flatten and rebuild, marker-free. Emit keys in preorder, then on the way back reconstruct using the bounds rule: each value claims the next position that fits its (low, high) window. The BST invariant replaces the null sentinels a general binary tree would require, making the encoding compact.

Key takeaways

  • A BST is a sorted sequence in disguise โ€” successor and rank are position questions, not full scans.
  • Inorder successor is O(h): leftmost of the right subtree, or the lowest left-turning ancestor.
  • Counting smaller-after has three idiomatic tools โ€” order-statistics BST, BIT over compressed values, or merge-sort inversion counting โ€” each about O(n log n).
  • BST serialization needs no markers: preorder plus the bounds rule reconstructs the exact tree.
  • The bounds rule does the rebuilding โ€” each value takes the first slot whose (low, high) window admits it.
  • Order replaces structure: because comparisons recover shape, you store values, not topology.

Order: Inorder Successor in BST โ†’ Count of Smaller Numbers After Self โ†’ Serialize and Deserialize BST.

Inorder Successor in BST

Core idea: The successor is either the leftmost node of p's right subtree, or the lowest ancestor you reached by turning left โ€” and a single root-to-node descent driven by comparisons finds both.


Problem, rephrased

Imagine a leaderboard stored as a binary search tree, keyed by score. Each player is a node. Someone points at a player and asks: "Who is ranked immediately above this player โ€” the next-higher score?"

That "next" is the inorder successor: the node with the smallest key that is strictly greater than p.val. Because an inorder traversal of a BST visits keys in sorted order, the successor is simply the node that comes right after p in that sorted sequence. If p already holds the top score, there is no successor โ€” return None.

You're given the tree root and a pointer to the node p (so you already know p.val). You do not get a list, and you do not get parent pointers.

Input (BST + node p) Output Why
Tree below, p = 15 node 17 smallest key > 15
Tree below, p = 6 node 7 next in sorted order
Tree below, p = 20 (the max) None nothing is larger

Reference tree for the table:

Reference BST: root 15 with children 6 and 20; inorder 2 3 4 6 7 13 15 17 20


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.