Range Sum Query – Immutable
Design a NumArray class that is initialized once with an integer array nums and then answers many range-sum queries. sumRange(left, right) must return the sum of the elements nums[left..right] inclusive. Queries may be called many times, so each one should be fast.
Open official problem prompt ↗Answer arbitrary range-sum questions on a fixed array instantly, no matter how many times we are asked.
Think of running mile markers on a highway. To find the distance between exit 12 and exit 30 you do not re-drive the road; you subtract marker 12 from marker 30. Prefix sums are those mile markers for the array.
- Input
- NumArray([-2, 0, 3, -5, 2, -1]); sumRange(0, 2)
- Output
- 1
- Why
- nums[0] + nums[1] + nums[2] = -2 + 0 + 3 = 1
1 <= nums.length <= 10^4-10^5 <= nums[i] <= 10^50 <= left <= right < nums.lengthAt most 10^4 calls to sumRange