Prefix sum · Easy
An analytics screen asks for totals over many periods of the same signed measurement series. The data is a fixed snapshot: all adjustments have already been applied. Recalculating every total by scanning the whole period will not scale to the request limit.
Return one exact total for each requested inclusive period in the original query order.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], queries: [integer, integer][] }
Fields
- nums is a fixed array of signed integer readings.
- queries is an array of inclusive zero-based [left,right] index pairs. Every pair satisfies 0 <= left <= right < nums.length.
- The values do not change between queries. If nums is empty, queries is empty. Neither input array may be modified.
Output
Return value
- Return an array of sums with one entry per query, preserving query order. Repeated queries produce repeated results.
- An empty query list returns []. Negative and zero totals are valid.
Constraints
- 0 <= nums.length <= 100000; 0 <= queries.length <= 100000.
- All input indexes and counts are integers.
- -1000000000 <= nums[i] <= 1000000000. Every sum fits exactly in a safe JSON integer.
Examples
Example 1
{
"nums": [
4,
-2,
7
],
"queries": [
[
0,
1
],
[
1,
2
],
[
0,
2
]
]
}Returns
[
2,
5,
9
]Example 2
{
"nums": [
-3
],
"queries": [
[
0,
0
],
[
0,
0
]
]
}Returns
[
-3,
-3
]Required complexity
O(n + q) time and O(n) auxiliary space excluding output