Range Sum Query — Prefix Sum
Prepare a helper from a fixed daily ledger that quickly answers many questions about the total across any span of days.
Prefix Sum · Easy
The problem
An insurer's claims ledger records the net payout or recovery for each day. Build an object that is given the fixed list of daily figures once, and then answers many questions of the form: what is the sum of the values from index left through index right (both included)?
The story
An insurer's claims ledger lists the net payout or recovery for each day, for a handful of days or for years, each between -1000 and 1000, and the figures never change. Auditors then ask many questions like "what's the total from day left through day right, both included?" Build an object that takes the ledger once and answers each question quickly.
What to return
- A test is a sequence of calls on one NumArray; the result is the list of outputs, one per call (the constructor gives nothing).
- sumRange(left, right) returns the sum of nums[left] + ... + nums[right].
- The list never changes after construction, and sumRange is called many times, so each query should be fast.
Constraints
- the sequence has 2 to 500 calls; the first is the constructor NumArray(nums) and the rest are sumRange
- 1 <= nums.length <= 1500 and -1000 <= nums[i] <= 1000
- 0 <= left <= right < nums.length for every sumRange call
- Your code may run at most 13,608 counted steps on the largest case.
Example
- Input
NumArray([4,-1,6,-3,2,5]), sumRange(0,2), sumRange(2,5), sumRange(0,5)- Output
—