In range query problems, the data structure can determine whether a solution meets the time limit. Updates between queries and query types guide the choice among prefix sums, difference arrays, Fenwick trees, segment trees, and monotonic deques.
Coding tests often ask for the sum, minimum, or maximum over an array range. They also ask for updates that add a value to an entire range. As input grows, a simple loop can exceed the time limit. Preprocessing and data structures must reduce the cost per query.
The choice depends on whether values change between queries and whether queries ask for sums, maxima, or minima.
Where range queries blow up
Rescanning a whole range costs (O(N)) per query. With (Q) queries, the total is (O(NQ)) and grows rapidly with input size. When (N) and (Q) each reach (10^5) to (5 \times 10^5), this approach is unlikely to pass.
As a rough guide, about (10^8) operations fit in one second (estimate; it varies by language and judge). At (N = 5 \times 10^5), (O(NQ)) exceeds (10^{11}) and times out. Preprocessing therefore has to bring each query down to (O(1)) or (O(\log N)).
Two questions determine the data structure. Do values change between queries? Does a query ask for a range sum or a range maximum/minimum?
Choosing based on whether updates occur
The table maps each situation to an approach. With no updates between queries, preprocessing is the default. With updates between queries, a tree structure is the default. A difference array counts as preprocessing because no query comes between its updates, even when there are many. For sliding window maxima and minima over an array whose values do not change, use a monotonic deque.
| Situation | Recommended approach | Complexity |
|---|---|---|
| No updates, many range sum queries | Prefix sum | Preprocess O(N), query O(1) |
| Many range updates, only the final values needed | Difference array | Update O(1), restore O(N) |
| Many queries and many updates | Segment tree | Query and update O(log N) |
| Sum queries with point updates | Fenwick tree (BIT) | Query and update O(log N) |
| Sliding window maximum/minimum | Monotonic deque | O(N) overall |
Turning the table into a decision flow gives the following. First check whether values change between queries. If they do not, split on the required result. If they do, split on the query and update types.
flowchart TD
Q0{"Do values change<br/>between queries"}
Q0 -->|"No"| Q1{"Required result"}
Q0 -->|"Yes"| Q2{"Query and update types"}
Q1 -->|"Range sum"| P1["Prefix sum<br/>preprocess O(N), query O(1)"]
Q1 -->|"Only range updates,<br/>then final values"| P2["Difference array<br/>update O(1), restore O(N)"]
Q1 -->|"Fixed-length window<br/>maximum/minimum"| P5["Monotonic deque<br/>O(N) overall"]
Q2 -->|"Sum query + point update"| P3["Fenwick tree<br/>query and update O(log N)"]
Q2 -->|"Range update or<br/>maximum/minimum query"| P4["Segment tree<br/>(lazy for range updates)<br/>query and update O(log N)"]
On the "No" branch, a prefix sum makes queries cheap after one preprocessing pass, and a difference array does so after one restoration. When values change often between queries, a tree structure is required instead.
Prefix sums and difference arrays
With no updates and many range sum queries, a prefix sum is the simplest answer. A prefix sum array stores the sum of elements 1 through (i) in advance. The sum over ([l, r]) is then a subtraction of two prefix values, computed in (O(1)).
def build_prefix(arr):
pre = [0] * (len(arr) + 1)
for i in range(1, len(arr) + 1):
pre[i] = pre[i - 1] + arr[i - 1]
return pre
def range_sum(pre, l, r): # 1-indexed, [l, r] inclusive
return pre[r] - pre[l - 1]
arr = [3, 1, 4, 1, 5, 9, 2, 6]
pre = build_prefix(arr)
print(range_sum(pre, 2, 5)) # 1 + 4 + 1 + 5 = 11Here pre[i] is the sum of elements 1 through (i). A 1-indexed array lets l - 1 in range_sum safely reach 0. Queries that include the first element therefore need no special case.
A difference array suits problems with many range additions when only the final array is needed. It records an addition of (v) over ([l, r]) in (O(1)) by changing two endpoints. After all updates, one prefix sum pass restores the array.
def range_update(diff, l, r, val): # add val over [l, r], 1-indexed
diff[l] += val
diff[r + 1] -= val
def restore(diff, n):
out = [0] * (n + 1)
for i in range(1, n + 1):
out[i] = out[i - 1] + diff[i]
return out[1:]
n = 6
diff = [0] * (n + 2) # one spare slot so r+1 is in range
range_update(diff, 2, 4, 10)
range_update(diff, 3, 6, 5)
print(restore(diff, n)) # [0, 10, 15, 15, 5, 5]diff[l] += val marks an increase of (v) starting at index (l). diff[r + 1] -= val cancels that increase after index (r). A prefix sum pass applies these marks to restore the array. The total cost of (Q) updates and one restoration is (O(N + Q)).
When point updates and range queries arrive together
When values change frequently and range sums are queried frequently, preprocessing alone is not enough. Changing one element in a prefix sum forces recomputation of everything after it, so updates cost (O(N)). This combination calls for a Fenwick tree or a segment tree.
A Fenwick tree, also called a binary indexed tree (BIT), handles both point updates and range sums in (O(\log N)). It stores partial sums split along the lowest set bit of the index (i & -i).
class Fenwick:
def __init__(self, n):
self.n = n
self.tree = [0] * (n + 1) # 1-indexed
def update(self, i, delta): # add delta at index i
while i <= self.n:
self.tree[i] += delta
i += i & -i
def prefix(self, i): # sum of 1..i
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def range_sum(self, l, r):
return self.prefix(r) - self.prefix(l - 1)
ft = Fenwick(8)
for idx, v in enumerate([3, 1, 4, 1, 5, 9, 2, 6], start=1):
ft.update(idx, v)
print(ft.range_sum(2, 5)) # 11
ft.update(3, 10) # element 3: 4 -> 14
print(ft.range_sum(2, 5)) # 21During an update, i += i & -i moves to the affected higher ranges. During a prefix sum query, i -= i & -i moves to the next range to accumulate.
A query removes the lowest set bit, one bit at a time. An update does not add one set bit at a time (for example, 3 → 4), but the position of the lowest set bit rises on every step. Both operations therefore repeat only (O(\log N)) times.
The short implementation makes a Fenwick tree a useful first choice for sum queries with point updates.
When updates operate on ranges or queries ask for a maximum or minimum, use a segment tree. This binary tree halves the range at each level. It answers range sum, minimum, and maximum queries in (O(\log N)). Lazy propagation defers updates to children so that range-wide additions are also fast.
Sliding window maximum and minimum go to a monotonic deque
Problems where a fixed-length window slides one step at a time and asks for the maximum or minimum deserve separate treatment. Rescanning the window each time costs (O(NK)), while a monotonic deque finishes in (O(N)) overall. Keeping the deque in descending order of value puts the current window maximum at the front at all times.
from collections import deque
def sliding_max(a, k):
dq = deque() # stores indices; the matching values stay in descending order
out = []
for i, x in enumerate(a):
while dq and a[dq[-1]] <= x:
dq.pop() # a smaller value can never become the maximum
dq.append(i)
if dq[0] <= i - k:
dq.popleft() # drop indices that fell out of the window
if i >= k - 1:
out.append(a[dq[0]])
return out
print(sliding_max([1, 3, -1, -3, 5, 3, 6, 7], 3))
# [3, 3, 5, 5, 6, 7]The key move is discarding the smaller trailing values when a new value arrives. Those values can never be the maximum while the new value remains in the window. Each index enters the deque once and leaves once, which keeps the total work at (O(N)).
Common mistakes
In range processing, small indexing mistakes lead to errors. The cases below are common.
- Mixing 0-indexed and 1-indexed conventions in a prefix sum, shifting the range boundary by one
- Skipping the bounds check on the
r + 1slot in a difference array update and running past the end of the array - Implementing a Fenwick tree 0-indexed, which tangles the
i & -imovement logic - Using a prefix sum for an update problem that needs a segment tree, making every update (O(N)) and timing out
Most of these mistakes become less frequent when the code uses one indexing convention throughout. A 1-indexed convention keeps boundary calculations consistent across prefix sums, difference arrays, and Fenwick trees. Before submitting, check a length-1 range and ranges at both ends of the array.
Summary
Updates and query types determine the data structure for most range processing problems. When values do not change between queries, a preprocessed prefix sum answers each range sum query in (O(1)). When there are many range updates but only the final values are needed, a difference array handles (Q) updates and one restoration in (O(N + Q)).
When values change between queries, use a tree. Sum queries with point updates use a Fenwick tree. Range updates or maximum/minimum queries use a segment tree. Both trees cost (O(\log N)) per query and per update.
Over an array whose values do not change, a monotonic deque handles fixed-length window maxima and minima in (O(N)) overall. These complexities come from standard algorithm analysis. Verify whether a solution passes by submitting it to problems such as Baekjoon Online Judge (BOJ) 11659, 2042, 10999, or 11003.