Solution: Range Sum Query - Immutable
Let's solve the Range Sum Query - Immutable problem using the Custom Data Structures pattern.
We'll cover the following
Statement
You are given an integer array, nums
, and you need to handle multiple queries of the following type:
Query: Calculate the sum of elements in
nums
between indicesi
andj
(inclusive), wherei <= j
.
Implement the NumArray
class to support the following operations efficiently:
Constructor
(NumArray(int[] nums)
: Initializes the object with the integer arraynums
.int sumRange(int i, int j)
: Returns the sum of the elements ofnums
between indicesi
andj
(inclusive), i.e., the sum ofnums[i] + nums[i + 1] + ... + nums[j]
.
Constraints:
nums.length
nums[i]
i
j
nums.length
At most,
calls will be made to sumRange
.
Solution
The algorithm uses a prefix sum array to enable efficient range sum queries. First, it constructs the prefix sum array, where each element at index nums
up to index
The steps of the algorithm are as follows:
Constructor: The constructor initializes the object with the input list nums
and calculates the prefix sum
array.
Initialize an array
sum
to store the prefix sums. The length of thesum
islen(nums) + 1
because we need an extra element to handle the sum of elements from the start (index0
). Initially,sum
is filled with zeros.The loop iterates through each element of the
nums
array to calculate the prefix sums.sum[i + 1] = sum[i] + nums[i]
updatessum
to store the cumulative sum of elements innums
.sum[i + 1]
is assigned the sum of all elements from the beginning ofnums
up to indexi
.The
i + 1
indexing ensures that the prefix sum at indexi
insum
corresponds to the sum of the firsti
elements ofnums
.
sumRange
method: This method efficiently calculates the sum of elements in nums
between indices i
and j
(inclusive) using the prefix sum array.
sum[j + 1]
: This gives the cumulative sum of elements up to indexj
innums
.sum[i]
: This gives the cumulative sum of elements up to indexi - 1
.The difference
sum[j + 1] - sum[i]
subtracts the sum of elements before indexi
, leaving only the sum of elements between indicesi
andj
(inclusive).
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.