Sum of Subarray Ranges (LeetCode 2104): Solution and Explanation
The range of a subarray is its largest element minus its smallest. Return the total of the ranges over every subarray of nums. For [1,2,3] the answer is 4. The total can pass 2^31, so it is returned as a 64-bit integer.
Intuition
Summing max - min over all subarrays is the same as summing every subarray's max and subtracting the sum of every subarray's min. The two halves can be solved separately.
An element is the maximum of a subarray exactly when the subarray contains it and does not reach the nearest larger element on either side. If those neighbours are at left and right, there are (i - left) choices of start and (right - i) choices of end.
A decreasing stack finds both neighbours at once: when right pops index mid, the element now on top is left. Each pop therefore adds nums[mid] * (mid - left) * (right - mid). The minima use an increasing stack in the same way.
Approach: Contribution counting with monotonic stacks
- Set
total = 0. Run the scan twice, first withsign = 1(maxima) and then withsign = -1(minima). Multiplying values bysignturns the min pass into a max pass. - Scan
rightfrom 0 ton, whereright = nis a sentinel that flushes the stack. - While the stack is not empty and
right == norsign * nums[top] < sign * nums[right], popmid. Letleftbe the new top, or -1 if the stack is empty. - Add
sign * nums[mid] * (mid - left) * (right - mid)tototalusing 64-bit arithmetic, then pushright. - Return
total.
Step-by-step example
nums = [1,2,3]
- Max pass: push 0. Index 1 (2) pops index 0 (1): left = -1, count 1 × 1 = 1, add 1.
- Index 2 (3) pops index 1 (2): left = -1, count 2 × 1 = 2, add 4. Push 2.
- The sentinel pops index 2 (3): left = -1, count 3 × 1 = 3, add 9. Sum of maxima = 14.
- Min pass: the stack only grows, so the sentinel pops 3 (count 1 × 1), then 2 (count 1 × 2), then 1 (count 1 × 3). Sum of minima = 3 + 4 + 3 = 10.
- Answer = 14 - 10 = 4.
Code: Python, Java, C++
1class Solution:
2 def subArrayRanges(self, nums: List[int]) -> int:
3 n = len(nums)
4 total = 0
5 for sign in (1, -1):
6 stack = []
7 for right in range(n + 1):
8 while stack and (right == n or sign * nums[stack[-1]] < sign * nums[right]):
9 mid = stack.pop()
10 left = stack[-1] if stack else -1
11 total += sign * nums[mid] * (mid - left) * (right - mid)
12 stack.append(right)
13 return total1class Solution {
2 public long subArrayRanges(int[] nums) {
3 int n = nums.length;
4 long total = 0;
5 for (int sign = 1; sign >= -1; sign -= 2) {
6 int[] stack = new int[n + 1];
7 int top = 0;
8 for (int right = 0; right <= n; right++) {
9 while (top > 0 && (right == n || (long) sign * nums[stack[top - 1]] < (long) sign * nums[right])) {
10 int mid = stack[--top];
11 int left = top > 0 ? stack[top - 1] : -1;
12 total += (long) sign * nums[mid] * (mid - left) * (right - mid);
13 }
14 stack[top++] = right;
15 }
16 }
17 return total;
18 }
19}1class Solution {
2public:
3 long long subArrayRanges(vector<int>& nums) {
4 int n = nums.size();
5 long long total = 0;
6 for (int sign = 1; sign >= -1; sign -= 2) {
7 vector<int> stack;
8 for (int right = 0; right <= n; right++) {
9 while (!stack.empty() && (right == n || (long long) sign * nums[stack.back()] < (long long) sign * nums[right])) {
10 int mid = stack.back();
11 stack.pop_back();
12 int left = stack.empty() ? -1 : stack.back();
13 total += (long long) sign * nums[mid] * (mid - left) * (right - mid);
14 }
15 stack.push_back(right);
16 }
17 }
18 return total;
19 }
20};Time and space complexity
O(n)
Each pass pushes and pops every index once.
O(n)
The stack can hold every index when the array is monotonic.
Other approaches
Expand every start (time O(n^2), space O(1))
For each start index, extend the end one step at a time while tracking the running max and min, and add max - min each time. Simple and fast enough for n = 1000.
Brute force (time O(n^3), space O(1))
Enumerate every subarray and scan it for its max and min. Too slow in principle and only useful as a checker.
Common mistakes
- Using strict comparisons on both sides (or non-strict on both). With equal values a subarray would be credited to two elements or to none. One side strict and the other non-strict credits it exactly once.
- Overflowing 32-bit integers. A single term
nums[mid] * (mid - left) * (right - mid)can reach 10^15, so cast before multiplying in Java, C++, C# and Go. - Forgetting the final flush. Elements still on the stack after the last index reign all the way to the right edge and must be popped with
right = n.
Frequently asked questions
Why does the popped element's new stack top mark its left boundary?
The stack is monotonic, so the element just below mid is the nearest one to its left that was not smaller (for the max pass). Everything between them was popped earlier because it was smaller than mid.
Is the O(n^2) solution accepted?
Yes, with n at most 1000 the expand-every-start loop runs about 500,000 steps. The stack solution is linear and is the one interviewers usually ask about as a follow-up.
How does this relate to Sum of Subarray Minimums?
That problem is exactly the min half of this one, taken modulo 10^9 + 7. Here you run the same counting for maxima as well and subtract.