Range Sum Query Immutable
To solve this coding challenge, we can utilize a technique known as prefix sum, which allows us to preprocess the given array in such a way that it facilitates efficient querying of subarray sums. The prefix sum array stores cumulative sums of the elements from the beginning of the array up to each index. This way, any subarray sum can be quickly computed using the difference between two prefix sums.
Explanation
Concept
- Prefix Sum Array :
-
Create a prefix sum array where each element at index
i
i-1
-
For example, if the input array is
[a, b, c, d]
[0, a, a+b, a+b+c, a+b+c+d]
- Querying Sum :
-
To find the sum of elements between indices
left
right
right+1
left
-
This works because the prefix sum at
right+1
right
left
left-1
[left, right]
- Initialization :
-
Initialize an empty list called
prefix_sum
-
Set the first element of
prefix_sum
0
- Building Prefix Sum Array :
- Iterate through each element of the input array.
-
Append the sum of the current element and the last element of the
prefix_sum
prefix_sum
-
Query Function (
sumRange
-
For each query, return the difference between the elements at indices
right + 1
left
prefix_sum
Steps in Pseudocode
Step-by-Step Explanation
Detailed Steps in Pseudocode
# Class definition for NumArray
class NumArray:
# Constructor to initialize the object with the given integer array
method __init__(nums):
# Initialize an empty prefix_sum list with an initial value of 0
prefix_sum = [0]
# Loop through each element in the given nums array
for each num in nums:
# Append the current prefix sum + current number to the prefix_sum list
prefix_sum.append(prefix_sum[-1] + num)
# Method to calculate the sum of elements between indices left and right (inclusive)
method sumRange(left, right):
# Return the difference between prefix_sum at index right+1 and prefix_sum at index left
return prefix_sum[right + 1] - prefix_sum[left]
Explanation
Initialization
-
The
__init__
nums
prefix_sum
-
By starting the
prefix_sum
Building Prefix Sum Array
-
For each element in
nums
prefix_sum
prefix_sum
-
This continuous accumulation ensures that each subsequent index in
prefix_sum
nums
Query Function (`sumRange`)
-
The
sumRange
left
right
-
By calculating the difference
prefix_sum[right + 1] - prefix_sum[left]
left
right
-
This difference works because
prefix_sum[right + 1]
right
prefix_sum[left]
left