Range Sum Query solution explained
For range sum queries on an array that never changes, precompute prefix sums once in O(n) and answer each query as prefix[right + 1] - prefix[left] in O(1). When values can be updated between queries, a prefix array would need O(n) work per update, so use a Fenwick tree (binary indexed tree) or a segment tree instead: both handle an update and a range sum in O(log n). The Fenwick tree is shorter to write; the segment tree extends to minimums, maximums and other operations.
By Evin JohnPublished 8 min read
The two versions of the problem
You are given an array of integers and then a stream of requests. In the first version, every request asks for the sum of the elements between two indices, inclusive. In the second, some requests instead set one element to a new value, and later sums must reflect the change. You design a class with a constructor and the methods sum_range(left, right) and, for the second version, update(index, value).
| Request | Result | Note |
|---|---|---|
| sum_range(1, 3) | 6 | -2 + 7 + 1 |
| sum_range(0, 5) | 12 | The whole array |
| sum_range(4, 4) | -3 | A single element |
| update(2, 0) | The 7 becomes 0 | |
| sum_range(1, 3) | -1 | -2 + 0 + 1 |
| sum_range(0, 5) | 5 | The total dropped by 7 |
What interviewers are after
The fixed version checks that you know to precompute, and it is usually a warm-up. The real conversation starts when the interviewer adds updates. They want to hear you compare the two simple designs, explain why neither works for a mix of updates and queries, and then reach for a tree structure. Writing a correct Fenwick tree from memory, and being able to say why the lowest set bit appears in it, is what makes the answer strong.
Version one: the array never changes
Keep a prefix array with a leading zero, so that prefix[i] is the sum of the first i elements. The sum from left to right is the total through right minus the total before left. The prefix sum pattern page covers this idea and its relatives (2D grids, difference arrays, counting with a hash map) in more depth.
class RangeSumStatic:
def __init__(self, nums):
self.prefix = [0]
for x in nums:
self.prefix.append(self.prefix[-1] + x)
def sum_range(self, left, right): # inclusive on both ends
return self.prefix[right + 1] - self.prefix[left]Version two: updates between queries
The two obvious designs each fail one side. Storing the plain array makes an update O(1) but a query O(n). Storing prefix sums makes a query O(1) but an update O(n), because changing one element shifts every later total. With q requests, either design can cost O(n · q). The fix is a structure where each stored total covers a block of elements, and any prefix can be assembled from O(log n) blocks, while each element belongs to only O(log n) blocks.
Fenwick tree
Number positions from 1. Position i stores the sum of a block that ends at i and whose length is the lowest set bit of i, written i & -i. So position 6 (binary 110) covers 2 elements, 5 and 6; position 8 covers all of 1 to 8; position 7 covers only itself. To get the sum of the first i elements, add tree[i], strip the lowest bit from i, and repeat until i is 0. To update element i, add the change to tree[i], add the lowest bit to i, and repeat while i is in range; that visits exactly the blocks containing i.
class RangeSumFenwick:
def __init__(self, nums):
self.n = len(nums)
self.nums = list(nums)
self.tree = [0] * (self.n + 1) # 1-based; tree[i] covers i - lowbit(i) + 1 .. i
for i, x in enumerate(nums, 1): # O(n) build: push each total to its parent
self.tree[i] += x
parent = i + (i & -i)
if parent <= self.n:
self.tree[parent] += self.tree[i]
def _prefix(self, i): # sum of the first i values
total = 0
while i > 0:
total += self.tree[i]
i -= i & -i # drop the lowest set bit
return total
def update(self, index, value):
delta = value - self.nums[index]
self.nums[index] = value
i = index + 1
while i <= self.n:
self.tree[i] += delta
i += i & -i # move to the next range that covers index
def sum_range(self, left, right):
return self._prefix(right + 1) - self._prefix(left)The constructor avoids n separate updates by pushing each finished block total up to the one block that contains it next, which makes the build O(n) instead of O(n log n). For [4, -2, 7, 1, -3, 5] after setting index 2 to 0, the internal array is [0, 4, 2, 0, 3, -3, 2]: position 2 holds 4 + -2, position 4 holds the first four elements, and position 6 holds -3 + 5. A query for indices 1 to 3 becomes prefix(4) - prefix(1) = 3 - 4 = -1.
Segment tree
A segment tree stores the values as leaves and, above them, a node for every pair, then every pair of pairs, up to a root holding the total. The compact version uses one array of size 2n: leaves at positions n to 2n - 1, and node i has children 2i and 2i + 1. An update changes a leaf and recomputes its ancestors. A query climbs from both ends of the range at once, adding any node that sits fully inside the range on the way up.
class RangeSumSegmentTree {
constructor(nums) {
this.n = nums.length;
this.tree = new Array(2 * this.n).fill(0); // leaves at n .. 2n - 1
for (let i = 0; i < this.n; i++) this.tree[this.n + i] = nums[i];
for (let i = this.n - 1; i > 0; i--) this.tree[i] = this.tree[2 * i] + this.tree[2 * i + 1];
}
update(index, value) {
let i = index + this.n;
this.tree[i] = value;
for (i = Math.floor(i / 2); i >= 1; i = Math.floor(i / 2)) {
this.tree[i] = this.tree[2 * i] + this.tree[2 * i + 1];
}
}
sumRange(left, right) {
// half-open [lo, hi) over the leaves, climbing one level per step
let lo = left + this.n;
let hi = right + this.n + 1;
let total = 0;
while (lo < hi) {
if (lo % 2 === 1) total += this.tree[lo++];
if (hi % 2 === 1) total += this.tree[--hi];
lo = Math.floor(lo / 2);
hi = Math.floor(hi / 2);
}
return total;
}
}The query loop treats the range as half-open, from lo up to but not including hi. If lo is a right child, its parent would include something to the left of the range, so take lo on its own and step past it. The same reasoning applies to hi from the other side. Replacing + with Math.min or Math.max, and starting the total at Infinity or -Infinity instead of 0, gives range minimum or maximum queries, which a Fenwick tree cannot do as simply.
Complexity
| Design | Build | Update | Range sum | Space |
|---|---|---|---|---|
| Plain array | O(1) | O(1) | O(n) | O(n) |
| Prefix sums | O(n) | O(n) | O(1) | O(n) |
| Fenwick tree | O(n) | O(log n) | O(log n) | O(n) |
| Segment tree (array of 2n) | O(n) | O(log n) | O(log n) | O(n) |
| Square-root blocks | O(n) | O(1) | O(√n) | O(n) |
Square-root decomposition, keeping one total for each block of about √n elements, is a middle ground worth naming if the interviewer asks for something simpler than a tree.
Edge cases
- left equal to right: the sum is one element.
- A range starting at index 0, which needs the leading zero or the 1-based shift.
- An update that sets a value equal to what is already there: the change is 0.
- An array of length 1.
- Large values in fixed-width languages, where long sums can overflow a 32-bit integer.
Mistakes
- Treating update(index, value) as add value. Most versions of this problem set the value, so compute the change from the stored old value.
- Mixing 0-based caller indices with the Fenwick tree's 1-based positions.
- Looping on i & -i when i is 0, which never terminates.
- Rebuilding the prefix array after every update and calling it efficient.
- Sizing a recursive segment tree too small; 4n is the usual safe size, while the iterative version needs exactly 2n.
How to explain it out loud
Fictional example
- Candidate
- If the array never changed, I'd store prefix sums and answer each query with one subtraction.
- Interviewer
- Now values can change.
- Candidate
- Then one update could shift up to n prefix totals. I'd use a Fenwick tree: each position stores a block whose length is its lowest set bit, so any prefix is a sum of at most log n blocks, and each element sits in at most log n blocks.
- Candidate
- Update and query are both log n. Since update sets a value, I'll keep a copy of the array to compute the difference.
Related problems
The prefix sum pattern is the place to start if the fixed version felt new. Subarray Sum Equals K uses running totals with a hash map instead of a tree. For other structures that answer repeated queries quickly, see Find Median from Data Stream, and the next problems in this set, Number of Provinces and Keys and Rooms, switch to graph search.
Rehearsing with Natively
Fenwick trees are short but easy to garble under pressure. As you study, Natively can take a screenshot of the problem on Mac or Windows and show an approach with code in its overlay, so you can check your bit arithmetic against it. When you practice explaining the trade-off between the designs out loud, it keeps a transcript you can read back. The AI interview assistant page has the details.
Questions people ask
How do you solve Range Sum Query on a fixed array?
Build a prefix array with a leading zero in O(n), then answer each query as prefix[right + 1] - prefix[left] in O(1).
How do you handle updates in Range Sum Query?
Use a Fenwick tree or a segment tree. Both support updating one element and summing a range in O(log n), where a prefix array would need O(n) per update.
How does a Fenwick tree work?
Position i stores the sum of a block ending at i whose length is the lowest set bit of i. A prefix sum adds blocks while stripping the lowest bit; an update walks up by adding the lowest bit.
Fenwick tree or segment tree?
A Fenwick tree is shorter and enough for sums. A segment tree handles minimum, maximum and other combine operations with the same O(log n) cost.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
