#1508
Range Sum of Sorted Subarray Sums
MediumArrayTwo PointersBinary SearchSortingPrefix SumPrefix SumHeap
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n² log n) |
| Space | O(n²) | O(n²) |
💡
Intuition
Time O(n² log n)Space O(n²)
Instead of generating all subarrays and sorting, we can use a prefix sum array to efficiently compute subarray sums and then use a min-heap to maintain the smallest sums in sorted order.
⚙️
Algorithm
4 steps- 1Step 1: Create a prefix sum array to store cumulative sums of the original array.
- 2Step 2: Use a min-heap to keep track of the smallest subarray sums as we iterate through the prefix sums.
- 3Step 3: For each prefix sum, compute all possible subarray sums ending at that index and add them to the heap.
- 4Step 4: Extract the smallest sums from the heap until we reach the right index, summing them as we go.
solution.py18 lines
1import heapq
2
3def rangeSum(nums, left, right):
4 n = len(nums)
5 prefix_sum = [0] * (n + 1)
6 for i in range(n):
7 prefix_sum[i + 1] = prefix_sum[i] + nums[i]
8 min_heap = []
9 for i in range(n):
10 for j in range(i + 1, n + 1):
11 subarray_sum = prefix_sum[j] - prefix_sum[i]
12 heapq.heappush(min_heap, subarray_sum)
13 result = 0
14 for _ in range(left - 1):
15 heapq.heappop(min_heap)
16 for _ in range(right - left + 1):
17 result = (result + heapq.heappop(min_heap)) % (10**9 + 7)
18 return resultℹ
Complexity note: The time complexity is O(n² log n) due to the sorting of subarray sums, while the space complexity remains O(n²) for storing these sums.
- 1Using prefix sums can significantly reduce the time taken to compute subarray sums.
- 2Sorting the sums allows for efficient retrieval of the desired range.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.