Kth smallest/largest
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Because an inorder walk of a search tree gives sorted order, the k-th smallest value is simply the k-th one you reach. You can stop right there instead of sorting everything, and walking from the other side gives the k-th largest.
Practical use cases
- Web app: Top 10 on a scoreboard. A game site shows the top 10 scores. The scores sit in an ordered tree, so the page walks from the highest end and stops after 10 values. It never touches the other 500,000 scores, and the board refreshes in a blink.
- Web app: Median and percentile on a stats page. An exam portal wants to show "your marks are at the 90th percentile". With the marks kept in an ordered tree, the code counts its way to the mark at that rank instead of sorting. The page does this for 20,000 students without sorting them again on every visit.
- System: Database ranking and search engines. Databases that answer "give me the 5th cheapest row" and search engines that rank results both depend on getting the position-k item from an ordered structure without sorting everything. Keeping the structure ordered once is cheaper than sorting again for each question.
The story: The Fourth Rank
On sports day, the 100-metre race results were stored in a BST: each runner's time was a node, faster times on the left, slower on the right. The headmaster announced, "The 4th fastest runner gets the bronze-plus ribbon!" Mira was asked to find that runner.
She remembered a secret about BSTs: if you read them left, node, right, the numbers come out in sorted order. So she walked the tree that way and kept a counter in her hand: 1... 2... 3... 4! The 4th runner she met was the answer. And she stopped immediately, since the rest of the tree did not matter.
Then the headmaster asked for the 3rd slowest to give a "never give up" medal. Mira just mirrored her walk: right, node, left. Now the slowest came first, and she counted to 3. Finding the kth smallest or largest is a simple counter on top of an inorder walk.
How to spot this problem, and where you need it
You need the item at a given rank, like the 3rd cheapest or 10th highest score, from data that is kept in a search tree or changes often.
Signs you need it
- Each request sorts a whole array only to read one or two positions from it.
- The wording says "k-th smallest", "k-th largest", "rank", "percentile" or "top N" over an ordered structure.
- The collection changes constantly, so re-sorting for every query is too costly.
Where to use it in a project
- Leaderboards and top-N widgets that show the best few of a very large ordered set.
- Statistics pages that compute percentiles and ranks over live data.
The solution
Walk the tree inorder (left, node, right) and keep a counter. Each time you handle a node, add one. When the counter reaches k, that node is the answer, so stop immediately. For the k-th largest, do the walk in the mirror order: right, node, left. No sorting, and no need to look at the rest.
Payoff: Before: sorting 500,000 scores to show 10. After: visiting only about 10 nodes beyond the walk down, so the board loads at once.
Explain it like I am 8
A BST read from left to right is a sorted line of kids. To find the 4th shortest, point at the shortest, then the next, and count to four. To find the 3rd tallest, start from the other end.
How it works, step by step
- Walk the tree in inorder: go as far left as you can, visit, then go right. Use a stack (or recursion).
- Every time you visit a node, add 1 to a counter.
- When the counter equals k, that node is your answer. Stop immediately.
- For the kth largest, swap left and right in the walk (go right first).
The code in four languages
PHP
<?php
class Node {
public ?Node $left = null;
public ?Node $right = null;
public function __construct(public int $val) {}
}
function insert(?Node $n, int $v): Node {
if ($n === null) return new Node($v);
if ($v < $n->val) $n->left = insert($n->left, $v);
else $n->right = insert($n->right, $v);
return $n;
}
// kth in sorted order (or from the biggest when $largest is true). Stops early.
function kth(?Node $root, int $k, bool $largest = false): ?int {
$stack = [];
$cur = $root;
while ($cur !== null || $stack) {
while ($cur !== null) { // go as far as possible first
$stack[] = $cur;
$cur = $largest ? $cur->right : $cur->left;
}
$cur = array_pop($stack); // visit
$k--;
if ($k === 0) return $cur->val; // this is the one
$cur = $largest ? $cur->left : $cur->right; // then the other side
}
return null; // fewer than k nodes
}
$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);
echo '4th smallest: ', kth($root, 4), PHP_EOL; // 6
echo '3rd largest: ', kth($root, 3, true), PHP_EOL; // 10
echo '20th smallest: ', kth($root, 20) ?? 'none', PHP_EOL; // noneJavaScript
class Node {
constructor(val) { this.val = val; this.left = null; this.right = null; }
}
function insert(n, v) {
if (n === null) return new Node(v);
if (v < n.val) n.left = insert(n.left, v);
else n.right = insert(n.right, v);
return n;
}
// kth in sorted order (or from the biggest when largest is true). Stops early.
function kth(root, k, largest = false) {
const stack = [];
let cur = root;
while (cur !== null || stack.length) {
while (cur !== null) { // go as far as possible first
stack.push(cur);
cur = largest ? cur.right : cur.left;
}
cur = stack.pop(); // visit
k--;
if (k === 0) return cur.val; // this is the one
cur = largest ? cur.left : cur.right; // then the other side
}
return null; // fewer than k nodes
}
let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);
console.log('4th smallest: ' + kth(root, 4)); // 6
console.log('3rd largest: ' + kth(root, 3, true)); // 10
console.log('20th smallest: ' + (kth(root, 20) ?? 'none')); // noneJava
import java.util.*;
public class Main {
static class Node {
int val;
Node left, right;
Node(int val) { this.val = val; }
}
static Node insert(Node n, int v) {
if (n == null) return new Node(v);
if (v < n.val) n.left = insert(n.left, v);
else n.right = insert(n.right, v);
return n;
}
// kth in sorted order (or from the biggest when largest is true). Stops early.
static Integer kth(Node root, int k, boolean largest) {
Deque<Node> stack = new ArrayDeque<>();
Node cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) { // go as far as possible first
stack.push(cur);
cur = largest ? cur.right : cur.left;
}
cur = stack.pop(); // visit
k--;
if (k == 0) return cur.val; // this is the one
cur = largest ? cur.left : cur.right; // then the other side
}
return null; // fewer than k nodes
}
public static void main(String[] args) {
Node root = null;
for (int v : new int[]{8, 3, 10, 1, 6, 14, 4, 7, 13}) root = insert(root, v);
System.out.println("4th smallest: " + kth(root, 4, false)); // 6
System.out.println("3rd largest: " + kth(root, 3, true)); // 10
Integer missing = kth(root, 20, false);
System.out.println("20th smallest: " + (missing != null ? missing : "none")); // none
}
}Go
package main
import "fmt"
type Node struct {
val int
left, right *Node
}
func insert(n *Node, v int) *Node {
if n == nil {
return &Node{val: v}
}
if v < n.val {
n.left = insert(n.left, v)
} else {
n.right = insert(n.right, v)
}
return n
}
// kth returns the kth value in sorted order (or from the biggest when largest
// is true). It stops early; ok is false if the tree has fewer than k nodes.
func kth(root *Node, k int, largest bool) (int, bool) {
var stack []*Node
cur := root
for cur != nil || len(stack) > 0 {
for cur != nil { // go as far as possible first
stack = append(stack, cur)
if largest {
cur = cur.right
} else {
cur = cur.left
}
}
cur = stack[len(stack)-1] // visit
stack = stack[:len(stack)-1]
k--
if k == 0 {
return cur.val, true // this is the one
}
if largest { // then the other side
cur = cur.left
} else {
cur = cur.right
}
}
return 0, false // fewer than k nodes
}
func main() {
var root *Node
for _, v := range []int{8, 3, 10, 1, 6, 14, 4, 7, 13} {
root = insert(root, v)
}
a, _ := kth(root, 4, false)
b, _ := kth(root, 3, true)
fmt.Println("4th smallest:", a) // 6
fmt.Println("3rd largest:", b) // 10
if _, ok := kth(root, 20, false); !ok {
fmt.Println("20th smallest: none")
}
}Time: O(h + k) · Extra space: O(h). Go down the height once, then take k steps; the stack holds at most one path.
Watch out for
- Doing a full inorder traversal into an array and then indexing. It works, but wastes time and memory when k is small.
- Counting from 0 instead of 1 (the 1st smallest is the minimum).
- Forgetting to handle k larger than the number of nodes.
Quick check
- Which walk gives BST keys from smallest to biggest?
- Preorder
- Inorder (left, node, right)
- Postorder
- How do you find the kth largest?
- Do the walk right-first instead of left-first
- Delete k nodes
- Sort the tree
- The 2nd smallest of our tree is...
- 1
- 3
- 4