Problem 907

Abstract / Summary

Given an array of integers, compute the sum of the minimum elements of every possible contiguous subarray.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0907.py

class Solution:
    def sumSubarrayMins(self, arr: List[int]) -> int:
        result = 0

        size = len(arr)
        # for each number find the distance of the next smaller number
        # do this for the left and the right side
        left  = [ None ] * size
        right = [ None ] * size

        # scan from left to right
        low = [] # position of last minimum
        for i in range(size):
            while low and arr[low[-1]] > arr[i]:
                low.pop()

            if low:
                left[i] = i - low[-1]
            else:
                left[i] = i + 1 # extend to the beginning

            low.append(i)

        # scan from right to left
        low = []
        for i in reversed(range(size)):
            while low and arr[low[-1]] >= arr[i]: # careful: count duplicate numbers only once, therefore >= instead of >
                low.pop()

            if low:
                right[i] = low[-1] - i
            else:
                right[i] = size - i # extend to the end

            low.append(i)

        # all combinations
        for a, l, r in zip(arr, left, right):
            result += a * l * r

        return result % 1_000_000_007
41 lines | 1232 bytes | submitted January 20, 2024 | GitHub   33% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 37% (700k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Monotonic Stack
  • Stack
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the sum of the minimum values of all contiguous sub-arrays of a given integer list. It does this by determining, for each element, how many sub-arrays treat that element as the minimum. The contribution of each element is then multiplied by the count of such sub-arrays and accumulated into the final result, which is returned modulo 1 000 000 007.

Core Data Structures

Two auxiliary arrays, left and right, store distances to the nearest smaller element on the left and right side of each position. A monotonic stack named low is reused for both directional scans. The stack holds indices of elements that form a non-decreasing sequence when viewed from the current scanning direction.

left  = [ None ] * size
right = [ None ] * size
low = []          # reused for left-to-right scan
low = []          # reused for right-to-left scan

Left-to-Right Scan

The first pass walks from the start of the array toward the end. For each index i, the algorithm removes indices from the stack while the element at the top of the stack is greater than the current element. After this pruning, the top of the stack (if any) points to the nearest element that is strictly smaller. The distance i - low[-1] becomes the count of possible left extensions where the current element remains the minimum. If the stack is empty, the element can extend all the way to the beginning, giving a distance of i + 1.

for i in range(size):
    while low and arr[low[-1]] > arr[i]:
        low.pop()

    if low:
        left[i] = i - low[-1]
    else:
        left[i] = i + 1

    low.append(i)

Right-to-Left Scan

The second pass processes indices in reverse order. The stack is cleared and then populated while moving from the end toward the start. The loop discards indices whose elements are greater than or equal to the current element. Using >= ensures that duplicate values are counted only once on the right side, preventing over-counting of sub-arrays where equal minima appear. After pruning, the distance to the next smaller element on the right is low[-1] - i. If no smaller element exists to the right, the distance extends to the end of the array, calculated as size - i.

for i in reversed(range(size)):
    while low and arr[low[-1]] >= arr[i]:
        low.pop()

    if low:
        right[i] = low[-1] - i
    else:
        right[i] = size - i

    low.append(i)

Combining Contributions

With left[i] representing the number of choices for the left boundary and right[i] the number of choices for the right boundary, the total number of sub-arrays where arr[i] is the minimum equals left[i] * right[i]. Multiplying this count by the element value yields its total contribution. The loop iterates over the three parallel sequences arr, left, and right, accumulating the weighted sum into result. The final modulo operation keeps the answer within the required range.

for a, l, r in zip(arr, left, right):
    result += a * l * r

return result % 1_000_000_007

Edge-Case Handling

The algorithm gracefully handles several boundary conditions:

  • Single-element array: Both scans assign a distance of 1 for left and right, resulting in a single sub-array contribution equal to the element itself.
  • All equal elements: The >= comparison in the right-to-left scan ensures that each equal element is considered the minimum for distinct sub-arrays without duplication, yielding the correct combinatorial count.
  • Strictly decreasing sequence: The left scan never pops any element because each new element is smaller, leading to left distances that grow with the index, while the right scan quickly empties the stack, giving right distances of 1. This correctly reflects that each element is the minimum only for sub-arrays ending at its position.
  • Strictly increasing sequence: The left scan frequently pops previous indices, resulting in left distances of 1 for each element, while the right scan accumulates larger right distances, matching the fact that each element serves as the minimum for sub-arrays extending to the right.

Performance Optimizations

The implementation achieves linear time execution by employing a monotonic stack for each directional scan. Each index is pushed onto the stack exactly once and popped at most once, guaranteeing that the total number of stack operations is proportional to the array length. This eliminates the need for nested loops that would otherwise lead to quadratic behavior.

Memory usage is kept minimal by reusing the same stack for both scans and by storing only two integer arrays of the same size as the input. The final accumulation loop operates directly on the zipped sequences, avoiding additional temporary structures.

The modulo operation is deferred until after the full accumulation, reducing the frequency of expensive arithmetic modulo operations while still ensuring the final result conforms to the required bound.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train of numbered toy blocks sitting in a row. This code wants to look at every single tiny group of blocks next to each other and find the smallest number in each group. Adding all those smallest numbers together can be a slow job, so instead of looking at every group one by one, the code plays a clever game.

First, it looks at each block and asks how far it can stretch to the left before hitting a block that is even smaller. Then, it does the same thing stretching to the right. It keeps these distances in two separate rows of boxes so it knows exactly how many groups each block is the boss of.

If a block knows its own number and how many groups it is the smallest in, it can quickly tell how much it contributes to the final big pile. Once the code knows exactly how much each block adds to the total, it finishes the math to find the final number. It is like carefully measuring how many times each toy is the smallest one in its group so the counting goes very fast.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.96 | σ = 1.07

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
chandansgowda Python
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
32 links | 18 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

5 solutions   January 20, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality