AlgoTales · Roadmap

Range minimum query

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

Where you will meet this in real life

Range minimum query (RMQ) asks for the smallest value between two positions. With a sparse table on fixed data, every question is answered with two lookups, which makes it a favourite building block inside other algorithms.

Practical use cases

  • Web app: Cheapest petrol along a route. A travel app has the petrol price at every pump along a highway, saved for the day. A traveller picks "from pump 12 to pump 48" and instantly sees the cheapest price, because two prepared blocks cover that stretch. The page answers while the traveller is still moving the selection handles, with no server calculation at all.
  • Web app: Lowest fare in a fixed price calendar. A flight or bus site shows a published fare calendar. A user selects any run of dates and sees the lowest fare. As the table is fixed for the day, each selection is just two lookups. The table is prepared once and every selection reuses it.
  • System: Lowest common ancestor and suffix arrays. Tools that find the nearest shared parent of two nodes in a tree, and text indexes built on suffix arrays, convert their questions into range minimum questions and rely on them being instant. The tree or text tool then runs far faster, since each tiny question costs two lookups rather than a scan.

The story: The Cheapest Tomatoes on the Highway

Aarav and Mira were travelling with Aarav's father to buy vegetables for the kirana store. Their auto-rickshaw passed 8 wholesale mandis in a row, and Papa had phoned each one in the morning for the day's tomato price. The prices are fixed for the day. All day long Papa kept asking, "Between the 3rd and 7th mandi, who is cheapest?" and a moment later, "Between the 1st and 4th?"

Aarav began to scan the price list for every question. "Too slow," said Mira. "Prices will not change today, so prepare a cheat sheet before we start." She wrote the cheapest price for every pair of neighbours, then for every group of four, then eight. "A group of four is just two pairs, so each row comes from the row above."

For "mandis 3 to 7" (five of them), Mira picked the biggest group that fits, size 4, and looked at two groups: one starting at mandi 3 and one ending at mandi 7. Both ready answers were on the sheet: 2 and 4. The cheaper was 2. Papa laughed: "Even if we crossed a thousand mandis, it would always be two lookups!" This is the range minimum query with a sparse table: heavy preparation once, lightning-fast answers after.

How to spot this problem, and where you need it

You keep asking for the smallest value between two positions in a list that does not change, and you want each answer in a constant, tiny amount of time.

Signs you need it

  • The problem says "minimum in range" and the array is never modified.
  • A min() over a slice runs inside a loop of thousands of questions.
  • Another algorithm (tree ancestor, text index) reduces to "smallest between i and j".
  • Memory is available for a table several times bigger than the list itself.

Where to use it in a project

  • Fixed price, rate or reading tables that users slice by range.
  • Behind the scenes of tree-ancestor and text-index features.

The solution

Make a table where row k holds, for each start position, the smallest value among the next 2^k items, filling each row from the previous one. To answer from l to r, find the biggest k so that 2^k fits in the range, and return the smaller of the table value at l and the table value at r minus 2^k plus 1.

Payoff: Before: scanning up to 100,000 values per question. After: two lookups and one comparison.

Explain it like I am 8

Before the game, you write, for every spot in a line of toys, the smallest toy among the next 1, 2, 4 and 8 toys. When a friend asks about toys 3 to 7, you peek at two notes that together cover them. The smaller of the two notes is the answer.

How it works, step by step

  1. Make the cheat sheet (levels): level 0 is the prices; each level above is built by taking the smaller of two blocks from the level below.
  2. For a question l to r, count how many items it has.
  3. Find the biggest block size not longer than that count. (Keep a small helper list that says, for each length, how many times you can halve it.)
  4. Look up two blocks of that size: the one starting at l, the one ending at r.
  5. Answer = the smaller of the two. Overlap is harmless for minimums.

The code in four languages

PHP

<?php
class SparseMin {
    private array $table;
    private array $lg;       // lg[len] = how many times len can be halved (the block level to use)

    public function __construct(array $a) {
        $n = count($a);
        $this->table = [$a];
        for ($k = 1; (1 << $k) <= $n; $k++) {
            $row = [];
            $half = 1 << ($k - 1);
            for ($i = 0; $i + (1 << $k) <= $n; $i++) {
                $row[] = min($this->table[$k - 1][$i], $this->table[$k - 1][$i + $half]);
            }
            $this->table[] = $row;
        }
        $this->lg = array_fill(0, $n + 2, 0);
        for ($len = 2; $len <= $n; $len++) {
            $this->lg[$len] = $this->lg[intdiv($len, 2)] + 1;   // one more halving than half the length
        }
    }

    // Cheapest among l..r (inclusive): two overlapping blocks
    public function query(int $l, int $r): int {
        $k = $this->lg[$r - $l + 1];
        return min($this->table[$k][$l], $this->table[$k][$r - (1 << $k) + 1]);
    }
}

$prices = [8, 3, 6, 2, 9, 4, 7, 5];
$rmq = new SparseMin($prices);
echo $rmq->query(3, 7) . PHP_EOL;   // 2  (blocks 3..6 and 4..7)
echo $rmq->query(0, 7) . PHP_EOL;   // 2  (the whole row)
echo $rmq->query(4, 6) . PHP_EOL;   // 4  (blocks 4..5 and 5..6)
echo $rmq->query(2, 2) . PHP_EOL;   // 6

JavaScript

class SparseMin {
  constructor(a) {
    const n = a.length;
    this.table = [a.slice()];
    for (let k = 1; (1 << k) <= n; k++) {
      const row = [];
      const half = 1 << (k - 1);
      for (let i = 0; i + (1 << k) <= n; i++) {
        row.push(Math.min(this.table[k - 1][i], this.table[k - 1][i + half]));
      }
      this.table.push(row);
    }
    this.lg = new Array(n + 2).fill(0);   // lg[len] = how many times len can be halved (the block level to use)
    for (let len = 2; len <= n; len++) {
      this.lg[len] = this.lg[len >> 1] + 1;   // one more halving than half the length
    }
  }

  // Cheapest among l..r (inclusive): two overlapping blocks
  query(l, r) {
    const k = this.lg[r - l + 1];
    return Math.min(this.table[k][l], this.table[k][r - (1 << k) + 1]);
  }
}

const prices = [8, 3, 6, 2, 9, 4, 7, 5];
const rmq = new SparseMin(prices);
console.log(rmq.query(3, 7));   // 2  (blocks 3..6 and 4..7)
console.log(rmq.query(0, 7));   // 2  (the whole row)
console.log(rmq.query(4, 6));   // 4  (blocks 4..5 and 5..6)
console.log(rmq.query(2, 2));   // 6

Java

import java.util.*;

public class Main {
    static class SparseMin {
        List<int[]> table = new ArrayList<>();
        int[] lg;       // lg[len] = how many times len can be halved (the block level to use)

        SparseMin(int[] a) {
            int n = a.length;
            table.add(a.clone());
            for (int k = 1; (1 << k) <= n; k++) {
                int[] prev = table.get(k - 1);
                int half = 1 << (k - 1);
                int[] row = new int[n - (1 << k) + 1];
                for (int i = 0; i < row.length; i++) {
                    row[i] = Math.min(prev[i], prev[i + half]);
                }
                table.add(row);
            }
            lg = new int[n + 2];
            for (int len = 2; len <= n; len++) {
                lg[len] = lg[len / 2] + 1;      // one more halving than half the length
            }
        }

        // Cheapest among l..r (inclusive): two overlapping blocks
        int query(int l, int r) {
            int k = lg[r - l + 1];
            return Math.min(table.get(k)[l], table.get(k)[r - (1 << k) + 1]);
        }
    }

    public static void main(String[] args) {
        int[] prices = {8, 3, 6, 2, 9, 4, 7, 5};
        SparseMin rmq = new SparseMin(prices);
        System.out.println(rmq.query(3, 7));    // 2  (blocks 3..6 and 4..7)
        System.out.println(rmq.query(0, 7));    // 2  (the whole row)
        System.out.println(rmq.query(4, 6));    // 4  (blocks 4..5 and 5..6)
        System.out.println(rmq.query(2, 2));    // 6
    }
}

Go

package main

import "fmt"

type SparseMin struct {
	table [][]int
	lg    []int // lg[len] = how many times len can be halved (the block level to use)
}

func NewSparseMin(a []int) *SparseMin {
	n := len(a)
	s := &SparseMin{table: [][]int{append([]int{}, a...)}}
	for k := 1; 1<<k <= n; k++ {
		half := 1 << (k - 1)
		var row []int
		for i := 0; i+(1<<k) <= n; i++ {
			row = append(row, min(s.table[k-1][i], s.table[k-1][i+half]))
		}
		s.table = append(s.table, row)
	}
	s.lg = make([]int, n+2)
	for length := 2; length <= n; length++ {
		s.lg[length] = s.lg[length/2] + 1 // one more halving than half the length
	}
	return s
}

// Query gives the cheapest among l..r (inclusive): two overlapping blocks.
func (s *SparseMin) Query(l, r int) int {
	k := s.lg[r-l+1]
	return min(s.table[k][l], s.table[k][r-(1<<k)+1])
}

func main() {
	prices := []int{8, 3, 6, 2, 9, 4, 7, 5}
	rmq := NewSparseMin(prices)
	fmt.Println(rmq.Query(3, 7)) // 2  (blocks 3..6 and 4..7)
	fmt.Println(rmq.Query(0, 7)) // 2  (the whole row)
	fmt.Println(rmq.Query(4, 6)) // 4  (blocks 4..5 and 5..6)
	fmt.Println(rmq.Query(2, 2)) // 6
}

Time: Build O(n log n), each query O(1) · Extra space: O(n log n). Preparation costs a few rows of answers; every question afterwards is just two lookups and one comparison. Data must not change.

Watch out for

  • Using it on data that changes. Any update makes many stored answers wrong, so use a segment tree.
  • Mixing up the right block start. It begins at r - blockSize + 1 so that it ends exactly at r.
  • Computing the block level with a slow loop for every question; precompute the halving list once.

Quick check

  1. What makes the sparse table query O(1)?
    • It sorts the range first
    • Two lookups of ready answers plus one comparison
    • It scans only half the range
  2. Range 3 to 7 has 5 items. Which block size is used?
    • 5
    • 8
    • 4
  3. Compared with a segment tree for range minimum, a sparse table...
    • Handles updates better
    • Answers faster but cannot handle updates
    • Uses less memory