Similar Problems

Similar Problems not available

Sum Of Subarray Ranges - Leetcode Solution

Companies:

  • jpmorgan

LeetCode:  Sum Of Subarray Ranges Leetcode Solution

Difficulty: Medium

Topics: stack array  

The Sum Of Subarray Ranges problem on Leetcode is a variation of the classic problem of finding the maximum subarray sum. In this problem, we are given an array of integers and a list of subarray ranges. We are supposed to find the sum of each subarray range.

Example:

Input: Array: [1, 2, 3, 4, 5] Subarray ranges: [[1,2], [2,4], [0,3]]

Output: [3, 9, 10]

Explanation: Subarray range [1,2] corresponds to [2,3] in the array, whose sum is 2+3 = 5. Subarray range [2,4] corresponds to [3,4,5] in the array, whose sum is 3+4+5 = 12. Subarray range [0,3] corresponds to [1,2,3,4] in the array, whose sum is 1+2+3+4 = 10. Hence, the output is [3, 9, 10].

Solution Approach:

To solve this problem, we can precompute the prefix sum array of the given array. The prefix sum of an array is the sum of all the elements up to that index. Hence, the i-th element of the prefix sum array is the sum of the first i elements of the given array.

Next, we can iterate through the given subarray ranges and calculate their sum by using the prefix sum array.

For example, to calculate the sum of subarray range [l,r], we can use the formula:

sum = prefixSum[r+1] - prefixSum[l]

Here, prefixSum[r+1] is the sum of the first (r+1) elements of the given array, and prefixSum[l] is the sum of the first l elements of the given array. Hence, subtracting prefixSum[l] from prefixSum[r+1] gives us the sum of the elements from l to r in the array.

We can use this formula to calculate the sum of each subarray range and store the results in a list, which we can return as the final output.

Python Code:

def getSumOfSubarrayRanges(nums, ranges): # Computing the prefix sum array prefixSum = [0]*(len(nums)+1) for i in range(1, len(nums)+1): prefixSum[i] = prefixSum[i-1] + nums[i-1]

# Calculating the sum of each subarray range
results = []
for l, r in ranges:
    results.append(prefixSum[r+1] - prefixSum[l])

return results

Input: nums = [1, 2, 3, 4, 5] ranges = [[1,2], [2,4], [0,3]] print(getSumOfSubarrayRanges(nums, ranges))

Output: [3, 9, 10]

Sum Of Subarray Ranges Solution Code

1