Build a prefix sum array in O(n) time, then answer each half-open range sum query in O(1) time in Java and Python.
Problem and input contract
Build a prefix array for a fixed sequence of n signed 32-bit integers. Each query uses zero-based bounds 0 ≤ left ≤ right ≤ n and returns the sum of elements from left up to right exclusive.
For [3, −2, 5, 1], [1, 3) returns 3 and [0, 4) returns 7. The empty array supports [0, 0), which returns 0. Two maximum Java int values sum to 4294967294.
Worked example
For [3, −2, 5, 1], the sum over [1, 3) is 3.
Start with 0, then append 3, 1, 6, and 7. For [1, 3), subtract prefix[1] = 3 from prefix[3] = 6. The result is 3, the sum of −2 and 5.
How the solution works
Each prefix stores the sum before its index. Subtract the prefix ending before left from the prefix ending before right.
Keep the initial zero so a range starting at index 0 uses the same subtraction. Require 0 ≤ left ≤ right ≤ n. Java uses long because sums can exceed int even when every input fits.
Python solution
def prefix_sums(nums):
prefix = [0]
for value in nums:
prefix.append(prefix[-1] + value)
return prefix
def range_sum(prefix, left, right):
return prefix[right] - prefix[left]Java solution
class Solution {
static long[] prefixSums(int[] nums) {
long[] prefix = new long[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
prefix[i + 1] = prefix[i] + nums[i];
}
return prefix;
}
static long rangeSum(long[] prefix, int left, int right) {
return prefix[right] - prefix[left];
}
}Approaches and complexity
Scanning each range costs O(right − left) and uses O(1) auxiliary space. Building the prefix array takes O(n) time and O(n) storage, then each query needs two reads and one subtraction. The preprocessing pays off when queries repeatedly cover long ranges.
| Approach | Time | Auxiliary space | Advantage | Limitation | Use case |
|---|---|---|---|---|---|
| Range scan | O(k) per query | O(1) | No preprocessing | Repeats work | Few short queries |
| Prefix sums | O(n) build, O(1) query | O(n) | Two reads per query | Rebuild after updates | Repeated queries on fixed data |
Common mistakes and interview follow-up
Build n + 1 entries so prefix[0] is zero. Convert inclusive ranges to half-open ranges by increasing the right endpoint by one. For frequent updates, consider a Fenwick tree.
Related practice: Find the First Occurrence with Binary Search.
Comments
Post a Comment