Coding Interview PatternsSum of Subarray Ranges
MediumMonotonic Stack

Sum of Subarray Ranges

Explanation & Solution

Description

Given an integer array nums, return the sum of all subarray ranges.

The range of a subarray is the difference between the largest and smallest elements in the subarray. A subarray is a contiguous non-empty sequence of elements within the array.

Examples

Input:nums = [1,2,3]
0
1
1
2
2
3

Output: 4

Explanation: The 6 subarrays are:

  • [1], range = 0
  • [2], range = 0
  • [3], range = 0
  • [1,2], range = 2 - 1 = 1
  • [2,3], range = 3 - 2 = 1
  • [1,2,3], range = 3 - 1 = 2

Sum of ranges = 0 + 0 + 0 + 1 + 1 + 2 = 4.

Input:nums = [1,3,3]
0
1
1
3
2
3

Output: 4

Explanation: The 6 subarrays are:

  • [1], range = 0
  • [3], range = 0
  • [3], range = 0
  • [1,3], range = 2
  • [3,3], range = 0
  • [1,3,3], range = 2

Sum of ranges = 0 + 0 + 0 + 2 + 0 + 2 = 4.

Input:nums = [4,-2,-3,4,1]
0
4
1
-2
2
-3
3
4
4
1

Output: 59

Explanation: The sum of all subarray ranges in the array is 59.

Constraints

  • 1 <= nums.length <= 1000
  • -10^9 <= nums[i] <= 10^9

Approach

Monotonic Stack pattern

1. Reframe the Problem

  • Instead of computing each subarray's range individually, observe that:
  • Sum of ranges = Sum of subarray maximumsSum of subarray minimums.
  • This separates the problem into two independent monotonic stack problems.

2. Compute Sum of Subarray Maximums

  • For each element nums[i], determine how many subarrays have nums[i] as their maximum.
  • Use a monotonic stack to find:
  • Previous Greater or Equal: the nearest index to the left where nums[j] >= nums[i], or -1 if none exists.
  • Next Greater: the nearest index to the right where nums[j] > nums[i], or n if none exists.
  • The number of subarrays where nums[i] is the max is leftCount * rightCount, where leftCount = i - prevGreaterOrEqual[i] and rightCount = nextGreater[i] - i.
  • Accumulate nums[i] * leftCount * rightCount into sumMax.

3. Compute Sum of Subarray Minimums

  • Similarly, for each element find how many subarrays have nums[i] as their minimum.
  • Use a monotonic stack to find:
  • Previous Less or Equal: the nearest index to the left where nums[j] <= nums[i], or -1.
  • Next Less: the nearest index to the right where nums[j] < nums[i], or n.
  • Accumulate nums[i] * leftCount * rightCount into sumMin.

4. Combine the Results

  • Return sumMax - sumMin, which equals the sum of all subarray ranges.

Key Insight

By decomposing the range into max and min contributions, each element's contribution to all subarrays can be computed in O(1) using boundary indices from a monotonic stack. The strict vs. non-strict inequality on each side prevents double-counting duplicates. Overall time complexity: O(n), space complexity: O(n).

Visualization

Input:
[1, 2, 3]
102132

No animation available

Left (L)Right (R)ConvergedDone
0 steps

Solution Code