AlgoTales · Roadmap

Predecessor/successor

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The successor of a value is the next bigger one in the tree and the predecessor is the next smaller. Finding them tells you what comes right after or right before an item, which is the heart of "next free slot" and "nearest value" features.

Practical use cases

  • Web app: Next free appointment slot. A clinic booking page has a patient asking for a 3 pm slot that is taken. The booked times are kept in a search tree, and the code finds the next booked time after 3 pm and the one before. It then offers the free gap between them instantly.
  • Web app: Next and previous item buttons. On an admin page listing orders sorted by number, "Next" and "Previous" buttons move to the neighbouring order. Using successor and predecessor on the ordered index avoids loading the entire list. Page changes feel immediate.
  • System: Event schedulers and ordered set APIs. Calendars and job schedulers ask "what is the next event after this time?" constantly. Ordered sets in programming languages offer calls such as "ceiling" and "lower_bound" that are this same operation. Behind a simple function call, a short walk down the tree does the work. You rarely write it yourself, but you often rely on it.

The story: The Batting Order Neighbours

In the mohalla cricket match, players batted in the order of their jersey numbers, smallest first. After player 3 got out, Kabir asked, "Who bats next?" Mira had the jersey numbers stored in a BST on a chart.

To find the next player after 3 she started at the top, 8, and asked: "Is 3 smaller than 8? Yes, so 8 is a possible next; I'll remember it, and go left." At 3: "Not smaller, go right." At 6: "3 is smaller, so 6 is a better candidate; remember it, go left." At 4: "Better again; remember it, go left." Nothing further left. The last remembered name was 4: the next batter!

Then Kabir asked about player 7. Starting from 8, she remembered 8, went left, then right, then right, and fell off. Answer: 8. The rule is simple: remember the last node where you turned left. That node is the successor. Turn it around (remember where you last turned right) and you get the predecessor, the player who batted just before.

How to spot this problem, and where you need it

You hold ordered data and often need the neighbour of a value, the next larger or the next smaller, even when that exact value is not in the data.

Signs you need it

  • You loop through a sorted list until you pass the value, just to see what comes next.
  • A feature offers "next available", "closest earlier" or "nearest later" results, such as for time slots, prices or IDs.
  • The statement asks for the inorder successor or predecessor of a node in a BST.

Where to use it in a project

  • Appointment and booking systems that must suggest the nearest free time around a requested time.
  • Next and previous navigation over ordered records and range queries in ordered indexes.

The solution

To find the successor of a value, start at the top and walk down as if searching for it. Each time you go left, remember the current node as a candidate, because it is bigger. Each time you go right, keep the old candidate. When you run out of nodes, the last candidate is the successor. For the predecessor, swap the roles of left and right.

Payoff: Before: scanning a list of 10,000 booked times for the neighbour. After: one downward walk of about 14 steps returns both neighbours.

Explain it like I am 8

Line up kids by height. The successor of a kid is the next taller kid; the predecessor is the next shorter one. In the tree you find them by walking down and remembering the closest bigger (or smaller) name you passed.

How it works, step by step

  1. Start at the root with succ = none.
  2. If the key is smaller than the current node, the current node could be the successor: remember it, then go left.
  3. Otherwise (key is equal or bigger) go right without remembering.
  4. When you fall off the tree, succ is the answer (none means the key is the maximum). For the predecessor, mirror everything: when the key is bigger, remember the node and go right.

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;
}

// next bigger key, or null if $key is the largest
function successor(?Node $root, int $key): ?int {
    $succ = null;
    $cur = $root;
    while ($cur !== null) {
        if ($key < $cur->val) { $succ = $cur->val; $cur = $cur->left; }   // candidate, go left
        else $cur = $cur->right;
    }
    return $succ;
}
// next smaller key, or null if $key is the smallest
function predecessor(?Node $root, int $key): ?int {
    $pred = null;
    $cur = $root;
    while ($cur !== null) {
        if ($key > $cur->val) { $pred = $cur->val; $cur = $cur->right; }  // candidate, go right
        else $cur = $cur->left;
    }
    return $pred;
}

$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);
echo 'successor of 3: ', successor($root, 3) ?? 'none', PHP_EOL;       // 4
echo 'successor of 7: ', successor($root, 7) ?? 'none', PHP_EOL;       // 8
echo 'successor of 14: ', successor($root, 14) ?? 'none', PHP_EOL;     // none
echo 'predecessor of 8: ', predecessor($root, 8) ?? 'none', PHP_EOL;   // 7
echo 'predecessor of 1: ', predecessor($root, 1) ?? 'none', PHP_EOL;   // none

JavaScript

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;
}

// next bigger key, or null if key is the largest
function successor(root, key) {
  let succ = null;
  let cur = root;
  while (cur !== null) {
    if (key < cur.val) { succ = cur.val; cur = cur.left; }    // candidate, go left
    else cur = cur.right;
  }
  return succ;
}
// next smaller key, or null if key is the smallest
function predecessor(root, key) {
  let pred = null;
  let cur = root;
  while (cur !== null) {
    if (key > cur.val) { pred = cur.val; cur = cur.right; }   // candidate, go right
    else cur = cur.left;
  }
  return pred;
}

let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);
console.log('successor of 3: ' + (successor(root, 3) ?? 'none'));       // 4
console.log('successor of 7: ' + (successor(root, 7) ?? 'none'));       // 8
console.log('successor of 14: ' + (successor(root, 14) ?? 'none'));     // none
console.log('predecessor of 8: ' + (predecessor(root, 8) ?? 'none'));   // 7
console.log('predecessor of 1: ' + (predecessor(root, 1) ?? 'none'));   // none

Java

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;
    }

    // next bigger key, or null if key is the largest
    static Integer successor(Node root, int key) {
        Integer succ = null;
        Node cur = root;
        while (cur != null) {
            if (key < cur.val) { succ = cur.val; cur = cur.left; }   // candidate, go left
            else cur = cur.right;
        }
        return succ;
    }

    // next smaller key, or null if key is the smallest
    static Integer predecessor(Node root, int key) {
        Integer pred = null;
        Node cur = root;
        while (cur != null) {
            if (key > cur.val) { pred = cur.val; cur = cur.right; }  // candidate, go right
            else cur = cur.left;
        }
        return pred;
    }

    static String show(Integer x) { return x == null ? "none" : String.valueOf(x); }

    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("successor of 3: " + show(successor(root, 3)));       // 4
        System.out.println("successor of 7: " + show(successor(root, 7)));       // 8
        System.out.println("successor of 14: " + show(successor(root, 14)));     // none
        System.out.println("predecessor of 8: " + show(predecessor(root, 8)));   // 7
        System.out.println("predecessor of 1: " + show(predecessor(root, 1)));   // 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
}

// successor returns the next bigger key; ok is false if key is the largest.
func successor(root *Node, key int) (succ int, ok bool) {
	cur := root
	for cur != nil {
		if key < cur.val { // candidate, go left
			succ, ok = cur.val, true
			cur = cur.left
		} else {
			cur = cur.right
		}
	}
	return succ, ok
}

// predecessor returns the next smaller key; ok is false if key is the smallest.
func predecessor(root *Node, key int) (pred int, ok bool) {
	cur := root
	for cur != nil {
		if key > cur.val { // candidate, go right
			pred, ok = cur.val, true
			cur = cur.right
		} else {
			cur = cur.left
		}
	}
	return pred, ok
}

func show(x int, ok bool) string {
	if !ok {
		return "none"
	}
	return fmt.Sprint(x)
}

func main() {
	var root *Node
	for _, v := range []int{8, 3, 10, 1, 6, 14, 4, 7, 13} {
		root = insert(root, v)
	}
	fmt.Println("successor of 3:", show(successor(root, 3)))     // 4
	fmt.Println("successor of 7:", show(successor(root, 7)))     // 8
	fmt.Println("successor of 14:", show(successor(root, 14)))   // none
	fmt.Println("predecessor of 8:", show(predecessor(root, 8))) // 7
	fmt.Println("predecessor of 1:", show(predecessor(root, 1))) // none
}

Time: O(h) · Extra space: O(1). One walk from the root to a leaf; no parent pointers are needed.

Watch out for

  • Using only the "smallest of the right subtree" rule. It fails when the key has no right child; then the answer is an ancestor.
  • Updating the candidate on every step instead of only when you turn left (successor) or right (predecessor).
  • Forgetting that the largest key has no successor and the smallest has no predecessor.

Quick check

  1. What is the successor of 7 in our tree?
    • 6
    • 8
    • 10
  2. When looking for a successor, when do we remember the current node?
    • When the key is smaller than it (we go left)
    • When the key is bigger than it
    • Always
  3. What is the predecessor of 8?
    • 3
    • 10
    • 7