Imagine you're working with a fixed dataset and need to efficiently answer multiple range sum queries. You're given an integer array nums and must handle numerous queries asking for the sum of elements between specific indices.
Your task: Implement the NumArray class that can:
NumArray(int[] nums)- Initialize with the integer arrayint sumRange(int left, int right)- Return the sum of elements from indexlefttoright(inclusive)
Key Challenge: Since there will be many queries, you need to optimize for query time rather than just solving it once. A naive approach of summing elements for each query would be too slow for large datasets with frequent queries.
Example: Given nums = [-2, 0, 3, -5, 2, -1]
โข sumRange(0, 2) returns 1 (sum of -2, 0, 3)
โข sumRange(2, 5) returns -1 (sum of 3, -5, 2, -1)
Input & Output
Visualization
Time & Space Complexity
After O(n) preprocessing, each query is answered in constant time using simple subtraction
Additional array to store prefix sums, same size as input array
Constraints
- 1 โค nums.length โค 104
- -105 โค nums[i] โค 105
- 0 โค left โค right < nums.length
- At most 104 calls will be made to sumRange