← Back to Algorithms, page 3

algorithms-0058 · Medium mid

Kth smallest element in a BST: return the k-th smallest value, and explain how to support frequent queries on a tree that changes.

Inorder traversal of a BST visits values in ascending order, so run an iterative inorder and stop at the k-th popped node: O(h + k) time and O(h) space. If the tree is modified often and queried often, store each node's subtree size; then the k-th value is found in O(h) by comparing k with the left subtree size.

Full answer

Problem

Given the root of a BST and an integer k (1-indexed), return the k-th smallest value.

Example: inserting 5, 3, 6, 2, 4, 1 gives a BST whose 3rd smallest value is 3.

Constraints: 1 <= k <= n <= 10^4; values are unique. Follow-up: the BST is modified often and kth-smallest is called often.

Brute force

Do a full inorder traversal into a list and return list[k - 1]. Correct, O(n) time and O(n) space, and it ignores that the answer may come early.

Optimal approach

Iterative inorder with early exit: push the left spine, pop a node, decrement k, return when k reaches 0, otherwise move to the right child.

For the follow-up, augment every node with size (nodes in its subtree), maintained on insert and delete. At a node, let L = size(left): if k <= L go left; if k == L + 1 return the node; else set k -= L + 1 and go right.

Why it works

Inorder visits the left subtree (all smaller values), then the node, then the right subtree, so the m-th popped node is the m-th smallest. In the augmented version, L counts exactly the values smaller than the current node within its subtree, so comparing k against L tells which side contains the answer.

Complexity

Early-exit inorder: O(h + k) time, O(h) space. Augmented tree: O(h) per query and O(h) extra work per insert or delete to update sizes; with a balanced tree (red-black, AVL, treap) h is O(log n).

Code

python
import random


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right
        self.size = 1                    # subtree size, used by the order-statistic version


def kth_smallest(root, k):
    """Iterative inorder that stops at the k-th node. O(h + k) time, O(h) space."""
    stack, node = [], root
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        k -= 1
        if k == 0:
            return node.val
        node = node.right
    raise ValueError("k is larger than the tree size")


def insert(root, v):
    """BST insert that maintains subtree sizes."""
    if root is None:
        return TreeNode(v)
    root.size += 1
    if v < root.val:
        root.left = insert(root.left, v)
    else:
        root.right = insert(root.right, v)
    return root


def kth_by_size(root, k):
    """O(h) per query when every node stores its subtree size."""
    node = root
    while node:
        left = node.left.size if node.left else 0
        if k <= left:
            node = node.left
        elif k == left + 1:
            return node.val
        else:
            k -= left + 1
            node = node.right
    raise ValueError("k is larger than the tree size")


if __name__ == "__main__":
    root = None
    for v in (5, 3, 6, 2, 4, 1):
        root = insert(root, v)
    assert [kth_smallest(root, k) for k in range(1, 7)] == [1, 2, 3, 4, 5, 6]
    assert kth_by_size(root, 3) == 3
    try:
        kth_smallest(root, 7)
        assert False
    except ValueError:
        pass
    rng = random.Random(58)
    for _ in range(300):
        vals = rng.sample(range(1000), rng.randint(1, 40))
        root = None
        for v in vals:
            root = insert(root, v)
        k = rng.randint(1, len(vals))
        assert kth_smallest(root, k) == kth_by_size(root, k) == sorted(vals)[k - 1]
    print("all tests passed")

Save as b58_kth_smallest_bst.py and run python3 b58_kth_smallest_bst.py. It prints all tests passed (Python 3.13.5).

Edge cases

k = 1 (leftmost node) and k = n (rightmost). k larger than n (raise or return an error). A skewed BST where h = n. Duplicate values, if allowed, need a policy for which side holds equals.

Pattern

Inorder as sorted iteration, plus order-statistic trees for rank queries. The same augmentation answers "how many values are less than x" and supports sliding-window medians with a balanced BST.

python
import random


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right
        self.size = 1                    # subtree size, used by the order-statistic version


def kth_smallest(root, k):
    """Iterative inorder that stops at the k-th node. O(h + k) time, O(h) space."""
    stack, node = [], root
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        k -= 1
        if k == 0:
            return node.val
        node = node.right
    raise ValueError("k is larger than the tree size")


def insert(root, v):
    """BST insert that maintains subtree sizes."""
    if root is None:
        return TreeNode(v)
    root.size += 1
    if v < root.val:
        root.left = insert(root.left, v)
    else:
        root.right = insert(root.right, v)
    return root


def kth_by_size(root, k):
    """O(h) per query when every node stores its subtree size."""
    node = root
    while node:
        left = node.left.size if node.left else 0
        if k <= left:
            node = node.left
        elif k == left + 1:
            return node.val
        else:
            k -= left + 1
            node = node.right
    raise ValueError("k is larger than the tree size")


if __name__ == "__main__":
    root = None
    for v in (5, 3, 6, 2, 4, 1):
        root = insert(root, v)
    assert [kth_smallest(root, k) for k in range(1, 7)] == [1, 2, 3, 4, 5, 6]
    assert kth_by_size(root, 3) == 3
    try:
        kth_smallest(root, 7)
        assert False
    except ValueError:
        pass
    rng = random.Random(58)
    for _ in range(300):
        vals = rng.sample(range(1000), rng.randint(1, 40))
        root = None
        for v in vals:
            root = insert(root, v)
        k = rng.randint(1, len(vals))
        assert kth_smallest(root, k) == kth_by_size(root, k) == sorted(vals)[k - 1]
    print("all tests passed")

Early-exit iterative inorder and a size-augmented query, both checked against sorted values on random BSTs.

Complexity

Time: O(h + k) inorder; O(h) with subtree sizes. Space: O(h). Keeping sizes costs O(h) per update; balancing keeps h at O(log n).

By level

Fresher: Uses inorder to list values in order and stops at the k-th one. Explains why inorder of a BST is sorted.

Mid: Writes the early-exit iterative version and the size-augmented walk, and explains the update cost. Handles k out of range.

Senior: Discusses order-statistic trees in production libraries, B-trees with counts for on-disk rank queries, and the trade-off between maintaining counts on writes versus scanning on reads. Picks the approach from the measured read to write ratio.

Key points

  • Inorder of a BST is ascending
  • Stop as soon as k nodes are popped
  • Subtree sizes turn the query into a single root-to-leaf walk
  • Sizes must be updated on insert and delete
  • Balanced trees keep h logarithmic

Common mistakes

  • Collecting the whole inorder list when early exit is possible
  • Off-by-one with 1-indexed k
  • Forgetting to update sizes on deletion
  • Claiming O(log n) without a balanced tree

Follow-ups

  • How do you find the k-th largest instead?
  • How would you support rank(x), the number of values below x?
  • What if the tree is too large for memory and lives on disk?

Tips

  • Mention O(h + k), not O(n), for early exit
  • Bring up subtree sizes for the follow-up
  • Say what keeps h small

Evaluation rubric

  • Correct early-exit traversal
  • Correct augmented query
  • Discusses update cost
  • Correct complexity in terms of h