We need to build a data structure that preprocesses an integer array so we can answer range sum queries efficiently. Each query gives us two indices, left and right, and asks for the sum of all elements between those positions (inclusive).
The array is immutable: it never changes after construction. That means we can precompute data once during initialization and reuse it across all queries. The design question is what to precompute so each query runs as fast as possible.
nums.length <= 10^4 and at most 10^4 calls to sumRange → If each query scans the range in O(n), total work reaches O(n * q) = O(10^8). That is enough to matter, so O(1) per query is the target.nums[i] can be negative → Sums are not monotonic, so we cannot prune ranges based on partial sums. Prefix sums still work because subtraction handles negatives correctly.-10^5 <= nums[i] <= 10^5 with up to 10^4 elements → The largest possible total sum is about 10^9, which fits in a signed 32-bit integer. No overflow handling is needed.Do exactly what the problem says: for each sumRange call, loop from left to right and add up the elements. No preprocessing is needed.
This holds up for a small number of queries, but it repeats work. A query for sumRange(0, 5) followed by sumRange(0, 3) re-adds elements that were already summed in the first call. Every query starts over from the beginning of its range.
sumRange(left, right) call, initialize a running sum to 0.left to right, adding each element to the running sum.Every query still loops through its range. Since the array never changes, the next approach precomputes cumulative sums once and answers each query with a single subtraction in O(1).
If we know the sum of elements from index 0 up to any index, we can compute the sum of any subarray by subtracting two of those running totals.
Define prefix[i] as the sum of all elements from index 0 to index i - 1. Then:
sum(left, right) = prefix[right + 1] - prefix[left]prefix[right + 1] is the sum of elements from 0 to right. We don't want elements 0 through left - 1, so we subtract prefix[left], which is exactly that unwanted portion. What remains is the sum from left to right.
We build this prefix array once during construction, and every query becomes one subtraction.
We size the array at n + 1 and set prefix[0] = 0 so the formula stays uniform when left = 0. With this layout, prefix[left] for left = 0 is the padding zero, so prefix[right + 1] - prefix[0] correctly returns the sum from index 0.
Without the padding, the query would need a branch: return prefix[right] when left is 0, and prefix[right] - prefix[left - 1] otherwise. The leading zero removes that special case.
prefix array of size n + 1, where n is the length of nums.prefix[0] = 0 (sum of zero elements).i from 0 to n - 1, set prefix[i + 1] = prefix[i] + nums[i].sumRange(left, right) call, return prefix[right + 1] - prefix[left].