The range query problem
25 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Range query problems ask us to aggregate elements in a subarray [L, R]—such as computing the sum, minimum, or maximum—while supporting dynamic updates. We examine naive arrays and prefix sums to see why traditional approaches break down when data changes.
Brute Force Array Scans and Prefix Sums
A range query asks for a value over a part of an array, such as the sum or minimum of elements from index l to r.
Consider an array of N numbers where you must answer queries for the sum of elements from index L to R. The naive approach scans the subarray one element at a time from L to R.
Example 1 · Range sum by scanning, brute force: O(N) per query, O(1) space
public class RangeScanDemo { static int query(int[] arr, int left, int right) { int sum = 0; for (int i = left; i <= right; i++) sum += arr[i]; // walk the whole range return sum; }
public static void main(String[] args) { int[] arr = {2, 4, 5, 7, 8, 9}; System.out.println("Sum [1, 3]: " + query(arr, 1, 3)); System.out.println("Sum [0, 4]: " + query(arr, 0, 4)); }}Sum [1, 3]: 16 Sum [0, 4]: 26
What this code does
- Each query walks from left to right and adds each element.
- With 100,000 queries on a 100,000-element array that is up to 10 billion additions.
- It prints 16 and 26, the same as the prefix-sum version.
Example 2 · Range sum with prefix sums, optimal for static data: O(1) per query, O(N) space
public class PrefixSumStaticDemo { public static int[] buildPrefix(int[] arr) { int n = arr.length; int[] pref = new int[n + 1]; for (int i = 0; i < n; i++) { pref[i + 1] = pref[i] + arr[i]; } return pref; }
public static int query(int[] pref, int l, int r) { return pref[r + 1] - pref[l]; }
public static void main(String[] args) { int[] arr = {2, 4, 5, 7, 8, 9}; int[] pref = buildPrefix(arr); System.out.println("Sum [1, 3]: " + query(pref, 1, 3)); System.out.println("Sum [0, 4]: " + query(pref, 0, 4)); }}Sum [1, 3]: 16 Sum [0, 4]: 26
What this code does
- Sum [1, 3] covers elements 4 + 5 + 7 = 16.
- Evaluated via pref[4] - pref[1] in O(1) arithmetic.
- Sum [0, 4] covers 2 + 4 + 5 + 7 + 8 = 26 via pref[5] - pref[0].
- Why faster: prefix[right + 1] - prefix[left] answers any range with two reads; the scan is paid once while building.
While a single query takes O(N) time in the worst case, executing Q queries takes O(Q * N) time. For 100,000 numbers and 100,000 queries, that is 10 billion operations, causing immediate timeouts. To optimize static queries, we precompute a prefix sum array in O(N) time. Each query pref[R] - pref[L - 1] evaluates in O(1) arithmetic, making static querying exceptionally fast.
Why Prefix Sums Break When Elements Are Updated
Prefix sums work brilliantly when the underlying data never changes. But what happens if the system frequently modifies individual elements, such as updating account balances or sensor readings?
Example 3 · Point update on a prefix array: O(N) per update
public class PrefixUpdateCostDemo { public static void update(int[] arr, int[] pref, int idx, int val) { int diff = val - arr[idx]; arr[idx] = val; // All subsequent prefix sums must be updated for (int i = idx + 1; i < pref.length; i++) { pref[i] += diff; } }
public static void main(String[] args) { int[] arr = {1, 2, 3, 4}; int[] pref = {0, 1, 3, 6, 10}; update(arr, pref, 1, 10); // change arr[1] from 2 to 10 (diff = +8) System.out.println("New pref: " + pref[0] + " " + pref[1] + " " + pref[2] + " " + pref[3] + " " + pref[4]); }}New pref: 0 1 11 14 18
What this code does
- Changing arr[1] requires updating pref[2], pref[3], and pref[4].
- Requires looping from idx + 1 to N, taking O(N) operations per update.
- Demonstrates why prefix sums fail when updates occur frequently.
When a single value at index i changes, every prefix sum from i to N - 1 becomes invalid. Updating the prefix sum array requires recomputing or shifting N - i entries, taking O(N) time per update. If you execute Q operations with an even mix of range queries and point updates, your system degrades to O(Q * N) overall time. We are stuck between two extremes: fast updates with slow queries, or fast queries with slow updates.
Comparing Invertible and Non-Invertible Aggregations
Another fundamental limitation of prefix sums is that they only support invertible operations like addition, multiplication, and XOR, where an evicted range can be subtracted away.
Example 4 · Choosing a range query structure
public class RangeStructureChooserDemo { public static String chooseStructure(boolean hasUpdates, boolean isStaticMin, boolean isPointUpdateOnly) { if (!hasUpdates && isStaticMin) return "Sparse Table (O(1) query, O(N log N) build)"; if (!hasUpdates) return "Prefix Sum (O(1) query, O(N) build)"; if (isPointUpdateOnly) return "Fenwick Tree (O(log N) query & point update, low memory)"; return "Segment Tree (O(log N) range query & range update with lazy propagation)"; }
public static void main(String[] args) { System.out.println(chooseStructure(false, true, false)); System.out.println(chooseStructure(true, false, true)); System.out.println(chooseStructure(true, false, false)); }}Sparse Table (O(1) query, O(N log N) build) Fenwick Tree (O(log N) query & point update, low memory) Segment Tree (O(log N) range query & range update with lazy propagation)
What this code does
- Static min queries are solved fastest by Sparse Tables in O(1) time.
- Dynamic point updates with sum queries are ideal for compact Fenwick Trees.
- Full range updates and queries require Segment Trees with lazy propagation.
For non-invertible operations like Range Minimum Query (RMQ) or Range Maximum Query, prefix sums cannot help at all: knowing min(0..R) and min(0..L - 1) does not tell you min(L..R) because the minimum might have been inside the excluded prefix. This structural tension motivates specialized data structures: Segment Trees, Fenwick Trees, and Sparse Tables, each balancing query and update operations in logarithmic or constant time.
Next step
Check your understanding
10 quick questions