Algo-Sim › Advanced Data Structures

Range Minimum Query (Sparse Table)

Medium · Advanced Data Structures · step through it in Java, Python and C++ on your own input

Precompute the minimum of every power-of-two block; any range is two overlapping blocks, so each query is O(1) on an array that never changes.

Problem

Design a class built from an integer array nums that never changes. query(left, right) returns the minimum of nums[left..right]. There are many queries, so each should take O(1) after preprocessing.

Constraints

Edge cases to test

Follow-up questions

Why can’t a sparse table answer range sums in O(1)?
The two blocks overlap, and an overlap counts twice for a sum. Sums need disjoint blocks (O(log n)) or a prefix-sum array.
What if values change?
Every block containing the index would need rebuilding (O(n)). Use a segment tree: O(log n) per update and query.
Where else does this show up?
LCA via an Euler tour plus RMQ, and suffix-array LCP queries; binary lifting is the same doubling idea on a tree.

Solution

Java

class SparseTable {
    private final int[][] st;
    private final int[] log;

    public SparseTable(int[] nums) {
        int n = nums.length;
        log = new int[n + 1];
        for (int i = 2; i <= n; i++) log[i] = log[i / 2] + 1;
        st = new int[log[n] + 1][];
        st[0] = nums.clone();
        for (int j = 1; j <= log[n]; j++) {
            int half = 1 << (j - 1);
            st[j] = new int[n - (1 << j) + 1];
            for (int i = 0; i < st[j].length; i++) {
                st[j][i] = Math.min(st[j - 1][i], st[j - 1][i + half]);
            }
        }
    }

    public int query(int left, int right) {
        int j = log[right - left + 1];
        return Math.min(st[j][left], st[j][right - (1 << j) + 1]);
    }
}

Python

class SparseTable:
    def __init__(self, nums):
        n = len(nums)
        self.log = [0] * (n + 1)
        for i in range(2, n + 1):
            self.log[i] = self.log[i // 2] + 1
        self.st = [nums[:]]
        for j in range(1, self.log[n] + 1):
            half = 1 << (j - 1)
            prev = self.st[j - 1]
            self.st.append([min(prev[i], prev[i + half])
                            for i in range(n - (1 << j) + 1)])

    def query(self, left, right):
        j = self.log[right - left + 1]
        return min(self.st[j][left], self.st[j][right - (1 << j) + 1])

C++

#include <bits/stdc++.h>
using namespace std;

class SparseTable {
  public:
    vector<vector<int>> st;
    vector<int> log;

    SparseTable(vector<int> &nums) {
        int n = int(nums.size());
        log.assign(n + 1, 0);
        for (int i = 2; i <= n; i++) log[i] = log[i / 2] + 1;
        st.assign(log[n] + 1, {});
        st[0] = nums;
        for (int j = 1; j <= log[n]; j++) {
            int half = 1 << (j - 1);
            st[j].resize(n - (1 << j) + 1);
            for (int i = 0; i < int(st[j].size()); i++) {
                st[j][i] = min(st[j - 1][i], st[j - 1][i + half]);
            }
        }
    }

    int query(int left, int right) {
        int j = log[right - left + 1];
        return min(st[j][left], st[j][right - (1 << j) + 1]);
    }
};

More Advanced Data Structures problems