Problem Description
Given an integer array, answer multiple queries asking for the sum of elements between two indices (inclusive).
Key Insights
- Precompute a prefix sum array during initialization.
- The sum for any given range can be computed in O(1) by subtracting the prefix sum at the starting index from the prefix sum at the ending index + 1.
- This approach makes use of extra O(n) space but provides fast queries.
Space and Time Complexity
Time Complexity: O(n) for preprocessing and O(1) per query.
Space Complexity: O(n) for storing the prefix sum array.
Solution
We build a prefix sum array such that each element at index i+1 represents the sum of the first i elements. For any query (left, right), the sum of elements between left and right is given by prefix[right+1] - prefix[left]. This approach leverages preprocessing to optimize query performance.