Sum of Subarray Ranges (LeetCode 2104): Solution and Explanation

Medium
Array
Stack
Monotonic Stack

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

  1. Set total = 0. Run the scan twice, first with sign = 1 (maxima) and then with sign = -1 (minima). Multiplying values by sign turns the min pass into a max pass.
  2. Scan right from 0 to n, where right = n is a sentinel that flushes the stack.
  3. While the stack is not empty and right == n or sign * nums[top] < sign * nums[right], pop mid. Let left be the new top, or -1 if the stack is empty.
  4. Add sign * nums[mid] * (mid - left) * (right - mid) to total using 64-bit arithmetic, then push right.
  5. Return total.

Step-by-step example

nums = [1,2,3]
  1. Max pass: push 0. Index 1 (2) pops index 0 (1): left = -1, count 1 × 1 = 1, add 1.
  2. Index 2 (3) pops index 1 (2): left = -1, count 2 × 1 = 2, add 4. Push 2.
  3. The sentinel pops index 2 (3): left = -1, count 3 × 1 = 3, add 9. Sum of maxima = 14.
  4. 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.
  5. 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 total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each pass pushes and pops every index once.

Space

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.