Skip to main content

Sum of Subarray Ranges - Solution & Explanation

MediumArrayStackMonotonic Stack17 min readAsked at: Amazon, Microsoft, Apple +6
Practice this problem

Problem Statement

You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.

Return the sum of all subarray ranges of nums.

A subarray is a contiguous non-empty sequence of elements within an array.

 

Example 1:

Input: nums = [1,2,3]
Output: 4
Explanation: The 6 subarrays of nums are the following:
[1], range = largest - smallest = 1 - 1 = 0 
[2], range = 2 - 2 = 0
[3], range = 3 - 3 = 0
[1,2], range = 2 - 1 = 1
[2,3], range = 3 - 2 = 1
[1,2,3], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.

Example 2:

Input: nums = [1,3,3]
Output: 4
Explanation: The 6 subarrays of nums are the following:
[1], range = largest - smallest = 1 - 1 = 0
[3], range = 3 - 3 = 0
[3], range = 3 - 3 = 0
[1,3], range = 3 - 1 = 2
[3,3], range = 3 - 3 = 0
[1,3,3], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.

Example 3:

Input: nums = [4,-2,-3,4,1]
Output: 59
Explanation: The sum of all subarray ranges of nums is 59.

 

Constraints:

  • 1 <= nums.length <= 1000
  • -109 <= nums[i] <= 109

 

Follow-up: Could you find a solution with O(n) time complexity?

Approach Overview

Problem Overview: You are given an integer array and must compute the sum of ranges for all subarrays. The range of a subarray equals max(subarray) - min(subarray). The task is to efficiently aggregate this value across every possible subarray.

Approach 1: Brute Force Expansion (O(n²) time, O(1) space)

Start a subarray at each index and expand it to the right. While expanding, maintain the current minimum and maximum values. Each time the window grows, update min and max, then add max - min to the result. This avoids recomputing min and max from scratch but still requires checking every subarray pair (i, j). The algorithm runs in O(n²) time with constant extra space. This approach is straightforward and useful for validating logic, but it becomes slow for large arrays because the number of subarrays grows quadratically.

Approach 2: Monotonic Stack Contribution Method (O(n) time, O(n) space)

The key observation is that each element contributes to multiple subarrays as both a maximum and a minimum. Instead of enumerating subarrays, count how many subarrays treat a value as their maximum and how many treat it as their minimum. The difference between these contributions determines its impact on the final sum.

Use monotonic stacks to find the previous and next greater elements for maximum contribution and the previous and next smaller elements for minimum contribution. For an index i, the number of subarrays where nums[i] is the maximum equals (i - prevGreater) * (nextGreater - i). Apply a similar calculation using smaller elements to count when it acts as the minimum. Multiply each count by the element value and accumulate the difference.

This transforms the problem into two linear scans using stack operations such as push, pop, and index tracking. Each element enters and leaves the stack once, producing O(n) time complexity and O(n) auxiliary space. The technique is widely used in problems involving subarray contributions and boundary discovery in stack-based algorithms on an array.

Recommended for interviews: Interviewers expect the monotonic stack solution because it demonstrates understanding of contribution counting and boundary discovery. Implementing the brute force approach first shows problem comprehension, but the O(n) stack solution shows strong algorithmic intuition and familiarity with advanced array techniques.

Approach 1: Brute Force Approach

The Brute Force Approach involves iterating over all possible subarrays of the given array. For each subarray, find the maximum and minimum elements, and calculate the difference. Sum all these differences to get the final answer. While this approach is simple, it is not efficient for larger arrays due to its quadratic time complexity.

This approach iterates over the array, using two nested loops where the outer loop sets the starting point of the subarray and the inner loop extends the subarray to all subsequent points. It calculates both the maximum and minimum for each subarray, computing their difference, which is accumulated into the total sum.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2), where n is the length of the array, due to the nested loop structure.
Space Complexity: O(1), no extra data structures are used apart from loop variables.

Try this approach in the editor →

Approach 2: Monotonic Stack Approach

The Monotonic Stack Approach optimizes the calculation by focusing on the contribution of each element as a maximum or minimum in various subarrays. By using two stacks, the solution efficiently determines the range extend of each number within the subarray, deriving the number of subarrays it could be the maximum or minimum of. This optimized approach emphasizes reducing redundant calculations commonly inherent in brute force methods.

This C solution centers upon leveraging two stacks for determining the role of each element both as a minimum and maximum across potential subarrays, to accumulate the distinct contribution of each element to the total subarray range.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), regarded as linear due to the stack operations limiting the number of necessary operations to a reduced count.
Space Complexity: O(n), for storing the elements in the stack structures.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Brute Force Approach

Time Complexity: O(n^2), where n is the length of the array, due to the nested loop structure.
Space Complexity: O(1), no extra data structures are used apart from loop variables.

Monotonic Stack Approach

Time Complexity: O(n), regarded as linear due to the stack operations limiting the number of necessary operations to a reduced count.
Space Complexity: O(n), for storing the elements in the stack structures.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force ExpansionO(n²)O(1)Useful for understanding the problem or verifying correctness on small arrays
Monotonic Stack ContributionO(n)O(n)Best choice for large inputs and expected solution in coding interviews

Video Solution

L10. Sum of subarray ranges | Stack and Queue Playlist • take U forward • 165,731 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Sum of Subarray Ranges easy or hard?
The problem is rated Medium on LeetCode. Understanding the brute force solution is straightforward, but deriving the O(n) monotonic stack approach requires familiarity with subarray contribution techniques and boundary discovery.
How to solve Sum of Subarray Ranges in O(n)?
Compute the contribution of each element as both a maximum and a minimum. Use monotonic stacks to find the previous and next greater elements for maximum contribution and previous and next smaller elements for minimum contribution. Multiply the distances to count how many subarrays include that element as the boundary.
What is the best approach for Sum of Subarray Ranges?
The optimal solution uses a monotonic stack to compute how many subarrays treat each element as a maximum and as a minimum. By calculating these contributions separately and subtracting them, the total range sum can be derived in O(n) time. This avoids enumerating every subarray.
Is Sum of Subarray Ranges asked at Google/Amazon/Meta?
Sum of Subarray Ranges represents a common interview pattern involving monotonic stacks and subarray contribution counting. Variants of this pattern frequently appear in interviews at companies like Amazon, Google, and Meta because they test deeper understanding of array boundaries and stack techniques.
What data structure is used in Sum of Subarray Ranges?
The optimal solution uses a monotonic stack. The stack maintains indices in increasing or decreasing order to efficiently find previous and next greater or smaller elements in linear time.
What is the time complexity of Sum of Subarray Ranges?
The brute force method runs in O(n^2) time because it checks every subarray while tracking the current minimum and maximum. The optimal monotonic stack approach runs in O(n) time since each element is pushed and popped from the stack at most once.
Sum of Subarray Ranges Python or Java solution approach
Python and Java implementations typically follow the same pattern: compute contributions for maximum values using a decreasing monotonic stack, then compute contributions for minimum values using an increasing stack. Both passes run in O(n) time and store indices in the stack.

Ready to solve this problem?

Practice Sum of Subarray Ranges with our built-in code editor and test cases.

Practice on FleetCode