Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Stack
MediumLC 907

Sum of Subarray Minimums (LeetCode 907)

Target Frequency:AmazonMetaNetflix

You're given an array of integers arr. Look at every contiguous subarray b of arr, take its minimum value min(b), and add all of those minimums together. Because that total can get huge, return it modulo 109 + 7.

Worked Examples

Example 1
Input:arr = [3,1,2,4]
Output:17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.
Example 2
Input:arr = [11,81,94,43,3]
Output:444
Explanation: Adding the minimum of each of the 15 subarrays gives 444.

⚖️Formal Constraints & Bounds

  • 1 <= arr.length <= 3 * 104

  • 1 <= arr[i] <= 3 * 104

Deep-Dive & Conceptual Insights

Core Insight

Do not enumerate O(N^2) subarrays. For each element arr[i], compute how many subarrays have arr[i] as their minimum using monotonic stack boundary spans: (i - prev) * (next - i) * arr[i].

Real-World Scenario & Production Applications

Risk variance analysis across streaming financial time series, minimum QoS window metrics in networking.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Monotonic Increasing Stack of Candidate Minimums

Maintain a stack of indices with strictly increasing values -- for each element, everything still on the stack when it's pushed is a value it could be the minimum FOR.

Mathematical Recurrence / Code Invariant
stack = []  # indices, values strictly increasing bottom to top
Worked on Paper

The Math, Step by Step

1. The sum, counted by element instead of by subarray

The problem asks for the sum of min⁡(b)\min(b)min(b) over every contiguous subarray bbb of arr. An array of nnn elements has n(n+1)2\frac{n(n + 1)}{2}2n(n+1)​ subarrays, so adding them one by one takes O(n2)O(n^2)O(n2) time or more.

The code turns the sum around. Each subarray's minimum is one element of arr, say arr[i]. So group the subarrays by the index of their minimum. Call cic_ici​ the number of subarrays whose minimum is arr[i]. Then

∑bmin⁡(b)=∑i=0n−1arr[i]⋅ci\sum_{b} \min(b) = \sum_{i=0}^{n-1} \text{arr}[i] \cdot c_i∑b​min(b)=∑i=0n−1​arr[i]⋅ci​

This is the contribution technique: each element adds its value once for every subarray it is the minimum of.

2. Counting the subarrays of one element

Fix an index iii. Let left[i] be the index of the nearest element to the left that is strictly smaller than arr[i], or −1-1−1 if there is none. Let right[i] be the index of the nearest element to the right that is smaller than or equal to arr[i], or nnn if there is none.

A subarray from index LLL to index RRR has arr[i] as its claimed minimum when it contains iii and stays between these two walls:

left[i]<L≤ii≤R<right[i]\text{left}[i] < L \le i \qquad i \le R < \text{right}[i]left[i]<L≤ii≤R<right[i]

LLL has i−left[i]i - \text{left}[i]i−left[i] choices, and RRR has right[i]−i\text{right}[i] - iright[i]−i choices. Every pair (L,R)(L, R)(L,R) gives a different subarray, so

ci=(i−left[i])⋅(right[i]−i)c_i = (i - \text{left}[i]) \cdot (\text{right}[i] - i)ci​=(i−left[i])⋅(right[i]−i)

3. Why the walls are right

Inside the walls, no element is smaller than arr[i]. So every subarray from LLL to RRR has minimum arr[i]. A subarray that reaches past left[i] contains a smaller element, so its minimum is not arr[i]. A subarray that reaches right[i] contains an element that is smaller or equal. When it is smaller, the minimum is not arr[i]. When it is equal, a later copy of the same value claims the subarray, as part 4 explains.

The code finds both walls in one pass with a stack of indices whose values increase from bottom to top. When arr[i] arrives, every index on top with a value greater than or equal to arr[i] is popped. For each popped index, arr[i] is the first value to its right that is smaller or equal, so the code sets its right to i. After the pops, the index on top, if any, holds a value strictly smaller than arr[i], so it is left[i].

4. Equal values: strict on one side only

When a subarray contains its minimum value twice, only one of the two indices may count it. The code is strict on the left side (left[i] is strictly smaller) and not strict on the right side (right[i] is smaller or equal). So the rightmost copy of the minimum claims the subarray.

Take arr = [2, 2]. Its three subarrays [2], [2] and [2, 2] have minimums that add up to 666. With the code's walls, index 0 gets right[0] = 1 and counts 1⋅1=11 \cdot 1 = 11⋅1=1 subarray. Index 1 gets left[1] = -1 and counts 2⋅1=22 \cdot 1 = 22⋅1=2 subarrays. The total is 2⋅1+2⋅2=62 \cdot 1 + 2 \cdot 2 = 62⋅1+2⋅2=6, which is correct.

If both walls allowed equal values to pass, both indices would count [2, 2], and the total would be 888. If both walls stopped at equal values, neither index would count [2, 2], and the total would be 444.

5. Example 1 by hand

arr = [3,1,2,4], so n=4n = 4n=4.

iiiarr[i]left[i]right[i]i−left[i]i - \text{left}[i]i−left[i]right[i]−i\text{right}[i] - iright[i]−icic_ici​arr[i]⋅ci\text{arr}[i] \cdot c_iarr[i]⋅ci​
03−1-1−111113
11−1-1−142366
22141224
34241114

The value 1 at index 1 is the minimum of 6 subarrays: LLL is 0 or 1, and RRR is 1, 2 or 3. The counts add up to 1+6+2+1=101 + 6 + 2 + 1 = 101+6+2+1=10, which is all 4⋅52=10\frac{4 \cdot 5}{2} = 1024⋅5​=10 subarrays. The sum is 3+6+4+4=173 + 6 + 4 + 4 = 173+6+4+4=17, the expected output.

6. Example 2 by hand

arr = [11,81,94,43,3], so n=5n = 5n=5.

iiiarr[i]left[i]right[i]cic_ici​arr[i]⋅ci\text{arr}[i] \cdot c_iarr[i]⋅ci​
011−1-1−141⋅4=41 \cdot 4 = 41⋅4=444
181031⋅2=21 \cdot 2 = 21⋅2=2162
294131⋅1=11 \cdot 1 = 11⋅1=194
343043⋅1=33 \cdot 1 = 33⋅1=3129
43−1-1−155⋅1=55 \cdot 1 = 55⋅1=515

The counts add up to 4+2+1+3+5=154 + 2 + 1 + 3 + 5 = 154+2+1+3+5=15 subarrays. The sum is 44+162+94+129+15=44444 + 162 + 94 + 129 + 15 = 44444+162+94+129+15=444. It is smaller than 109+710^9 + 7109+7, so the modulo leaves it unchanged, and the code returns 444, the expected output.

7. From the formulas to the code
FormulaIn sumSubarrayMins
nearest strictly smaller on the left, or −1-1−1left = [-1] * n and left[i] = stack[-1] if stack else -1
nearest smaller or equal on the right, or nnnright = [n] * n and right[stack.pop()] = i
pop while the top is greater than or equalwhile stack and arr[stack[-1]] >= arr[i]:
∑iarr[i]⋅(i−left[i])⋅(right[i]−i)\sum_i \text{arr}[i] \cdot (i - \text{left}[i]) \cdot (\text{right}[i] - i)∑i​arr[i]⋅(i−left[i])⋅(right[i]−i)sum(arr[i] * (i - left[i]) * (right[i] - i) for i in range(n))
the answer modulo 109+710^9 + 7109+7% MOD

Every index is pushed once and popped at most once, so the pass takes O(n)O(n)O(n) time. The arrays left and right and the stack take O(n)O(n)O(n) space.

Code Shape
Archetype Code Shape
Python
1for i in range(n):
2 while stack and arr[stack[-1]] >= arr[i]:
3 right[stack.pop()] = i
4 left[i] = stack[-1] if stack else -1
5 stack.append(i)
6total = sum(arr[i] * (i - left[i]) * (right[i] - i) for i in range(n))
7return total % (10**9 + 7)

Conceptual Narrative

Evaluating all O(N²) subarrays times out. Inverting the perspective—calculating how many subarrays each element serves as the minimum for—solves the problem in a single O(N) monotonic stack pass.

🧭 Conceptual Foundation & Pattern Intuition

A brute force calculates min⁡(A[i..j])\min(A[i..j])min(A[i..j]) for all O(N2)O(N^2)O(N2) subarrays, which is impossible for N=3⋅104N = 3 \cdot 10^4N=3⋅104. Instead of asking "what is the minimum of subarray [i..j][i..j][i..j]?", invert the question: "In how many subarrays is A[k] the minimum element?"\textbf{"In how many subarrays is } A[k] \textbf{ the minimum element?"}"In how many subarrays is A[k] the minimum element?" If A[k]A[k]A[k] is the minimum for CkC_kCk​ distinct subarrays, its total contribution to the answer is A[k]×CkA[k] \times C_kA[k]×Ck​. How do we calculate CkC_kCk​?

  • Find the Previous Less Element (PLE): the first index L<kL < kL<k where A[L]<A[k]A[L] < A[k]A[L]<A[k]. A[k]A[k]A[k] can extend k−Lk - Lk−L choices to the left.
  • Find the Next Less Element (NLE): the first index R>kR > kR>k where A[R]≤A[k]A[R] \le A[k]A[R]≤A[k]. A[k]A[k]A[k] can extend R−kR - kR−k choices to the right.
  • Total subarrays with A[k]A[k]A[k] as minimum: Ck=(k−L)×(R−k)C_k = (k - L) \times (R - k)Ck​=(k−L)×(R−k).
  • Asymmetric Tie-Breaking: To avoid double-counting subarrays when duplicate numbers exist (e.g. [2,2][2, 2][2,2]), use strict inequality (<<<) on one side and non-strict (≤\le≤) on the other!
👑 The Analogy: The King of the Valley Domain

Imagine each number in the array is a king ruling a valley. A king rules in both directions as long as the neighboring peaks are taller than him. His dominion to the left stops the moment he encounters a king strictly shorter than himself (LLL); his dominion to the right stops the moment he encounters a king shorter or equally tall (RRR). The number of subarrays in which he is the minimum is the product of his left expansion choices and his right expansion choices (k−L)×(R−k)(k - L) \times (R - k)(k−L)×(R−k).

🔑 Why It Works

One increasing stack gives both boundaries: an index popped by arr[i] gets right = i (the first smaller-or-equal value), and the index left under i is its previous strictly smaller value. Stopping at a strictly smaller value on the left and a smaller-or-equal value on the right gives every subarray exactly one minimum owner, so ties are never counted twice.

  • Double-counting duplicate values: Using strict inequalities on both left and right causes subarrays spanning identical minimums to be counted twice. Use < on left and <= on right.

  • Forgetting modulo arithmetic: Sum can grow astronomically; compute total = (total + nums[i] * left * right) % (10**9 + 7) on every addition.

  • Empty stack boundary off-by-one: When no smaller element exists to the left, distance is i−(−1)=i+1i - (-1) = i + 1i−(−1)=i+1. When no smaller element exists to the right, distance is n−in - in−i.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

The statement asks for the sum of min(b) over every contiguous subarray b, with arr.length up to 3 * 10^4: listing all O(N²) subarrays is too slow, so count each element's share instead (Contribution Technique).

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: arr[i] is the minimum of every subarray that starts in left[i] + 1 .. i and ends in i .. right[i] - 1, where left[i] is the previous strictly smaller index and right[i] the next smaller-or-equal index; the values at the indices in stack strictly increase from bottom to top.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Ties: pop while arr[stack[-1]] >= arr[i], so the right boundary is the next smaller-or-equal value and the left one the previous strictly smaller value. The same rule on both sides counts a tied subarray twice (< on both) or never (<= on both).

  • Modulo: the blueprint takes % MOD once, at the end, which is safe in Python; forgetting it returns a number above 10^9 + 7. In Java or C++, use 64-bit products and reduce on every addition.

  • Defaults: left starts at -1 and right at n, so an element with no smaller value on a side reaches the end of the array.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"This is the Contribution Technique. Listing all subarrays is O(n squared), so I flip the question: in how many subarrays is arr[i] the minimum? It stays the minimum until the first smaller value on each side, so with left[i] and right[i] as those boundaries it owns (i minus left[i]) times (right[i] minus i) subarrays. One increasing stack finds both in a single pass: when arr[i] pops an index, arr[i] is that index's right boundary, and whatever is left under i is its left boundary. The trap is ties: I pop on greater-or-equal, so the right side stops at an equal value and the left side only at a strictly smaller one, and each subarray is counted once. Then I sum value times share and take the modulo. Each index is pushed once and popped at most once: O(n) time, O(n) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the blueprint's two loops. The for i in range(n) loop pushes each index once with stack.append(i), and the inner while pops each index at most once (setting right[stack.pop()] = i), so across the whole loop there are at most N pushes and N pops: O(N) amortized, even though one step may pop many indices. left[i] = stack[-1] if stack else -1 is O(1) per step. The final sum(arr[i] * (i - left[i]) * (right[i] - i) for i in range(n)) does O(1) work per index: O(N). Total: O(N) + O(N) = O(N).

SPACE COMPLEXITY

O(N)

Look at the allocations: left and right hold N indices each, and stack holds at most N indices (on a strictly increasing array nothing is popped). The answer is one integer. Auxiliary space: O(N).

Formal Recurrence Relation

T(N)=2N⏟pushes + pops+N⏟sum=O(N)T(N) = \underbrace{2N}_{\text{pushes + pops}} + \underbrace{N}_{\text{sum}} = O(N)T(N)=pushes + pops2N​​+sumN​​=O(N)

Derivation Progression

One Pass Fills Both Boundaries

pushes=N,pops≤N\text{pushes} = N, \quad \text{pops} \le Npushes=N,pops≤N

When arr[i] pops an index, it becomes that index's right (the first smaller-or-equal value); the index left under i is left[i] (strictly smaller). Each index enters and leaves the stack at most once.

Share of Each Element

sharei=arr[i]⋅(i−left[i])⋅(right[i]−i)\text{share}_i = arr[i] \cdot (i - left[i]) \cdot (right[i] - i)sharei​=arr[i]⋅(i−left[i])⋅(right[i]−i)

O(1) per index: arr[i] is the minimum of every subarray starting in left[i] + 1 .. i and ending in i .. right[i] - 1.

Sum of Shares

Total=(∑i=0N−1sharei) mod (109+7)\text{Total} = \left(\sum_{i=0}^{N-1} \text{share}_i\right) \bmod (10^9 + 7)Total=(∑i=0N−1​sharei​)mod(109+7)

N more O(1) steps; Python takes the modulo once at the end.

Variable Definitions

NNN

Length of input array arr

Memory Architecture & Bounds

🟣 Call Stack

O(1) Non-recursive loops

🔵 Auxiliary Heap

O(N) For the left and right arrays and the monotonic stack

🟢 Output Space

O(1) One integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N) strictly increasing array: nothing is popped until the end.

Average Case

O(N)O(N)O(N).

Worst Case

O(N)O(N)O(N) strictly decreasing array: every index is popped by the next one.

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "sum of min(b) over all contiguous subarrays b", "modulo 109 + 7". Instead of iterating over all O(N2)O(N^2)O(N2) subarrays, invert the perspective: Contribution Counting. For each element arr[i]arr[i]arr[i], count the subarrays in which arr[i]arr[i]arr[i] is the minimum, ties going to one copy only.

CONSTRAINTS & BOUNDS

1≤arr.length≤3×1041 \le arr.length \le 3 \times 10^41≤arr.length≤3×104, 1≤arr[i]≤3×1041 \le arr[i] \le 3 \times 10^41≤arr[i]≤3×104. Time budget: O(N)O(N)O(N); the O(N2)O(N^2)O(N2) scan is about 4.5×1084.5 \times 10^84.5×108 subarrays. Modulo 109+710^9 + 7109+7.

FAANG PRODUCTION TRAPS & EDGE CASES

Overflow outside Python: one share arr[i]×(i−left[i])×(right[i]−i)arr[i] \times (i - left[i]) \times (right[i] - i)arr[i]×(i−left[i])×(right[i]−i) can reach about 3×104×1.5×104×1.5×104≈6.75×10123 \times 10^4 \times 1.5 \times 10^4 \times 1.5 \times 10^4 \approx 6.75 \times 10^{12}3×104×1.5×104×1.5×104≈6.75×1012, far past 32 bits, so Java and C++ need 64-bit products and a modulo on every addition; Python can reduce once at the end. On a stream, right is only known when a later value pops the index, so a share can be added only once its right boundary has arrived.

Core Algorithmic State Invariants

  1. Every Subarray Has Exactly One Owner

Take any subarray and its smallest value; if that value appears more than once, the rightmost copy owns it: its range stops at the first smaller-or-equal value on the right, so it reaches the end of the subarray, and at a strictly smaller value on the left, so it reaches the start. Every other copy's range stops at the next equal value. So each subarray is added exactly once.

Theory Context•Stack
MediumLC 907

Sum of Subarray Minimums (LeetCode 907)

Target Frequency:AmazonMetaNetflix

You're given an array of integers arr. Look at every contiguous subarray b of arr, take its minimum value min(b), and add all of those minimums together. Because that total can get huge, return it modulo 109 + 7.

Worked Examples

Example 1
Input:arr = [3,1,2,4]
Output:17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.
Example 2
Input:arr = [11,81,94,43,3]
Output:444
Explanation: Adding the minimum of each of the 15 subarrays gives 444.

⚖️Formal Constraints & Bounds

  • 1 <= arr.length <= 3 * 104

  • 1 <= arr[i] <= 3 * 104

Deep-Dive & Conceptual Insights

Core Insight

Do not enumerate O(N^2) subarrays. For each element arr[i], compute how many subarrays have arr[i] as their minimum using monotonic stack boundary spans: (i - prev) * (next - i) * arr[i].

Real-World Scenario & Production Applications

Risk variance analysis across streaming financial time series, minimum QoS window metrics in networking.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Monotonic Increasing Stack of Candidate Minimums

Maintain a stack of indices with strictly increasing values -- for each element, everything still on the stack when it's pushed is a value it could be the minimum FOR.

Mathematical Recurrence / Code Invariant
stack = []  # indices, values strictly increasing bottom to top
Worked on Paper

The Math, Step by Step

1. The sum, counted by element instead of by subarray

The problem asks for the sum of min⁡(b)\min(b)min(b) over every contiguous subarray bbb of arr. An array of nnn elements has n(n+1)2\frac{n(n + 1)}{2}2n(n+1)​ subarrays, so adding them one by one takes O(n2)O(n^2)O(n2) time or more.

The code turns the sum around. Each subarray's minimum is one element of arr, say arr[i]. So group the subarrays by the index of their minimum. Call cic_ici​ the number of subarrays whose minimum is arr[i]. Then

∑bmin⁡(b)=∑i=0n−1arr[i]⋅ci\sum_{b} \min(b) = \sum_{i=0}^{n-1} \text{arr}[i] \cdot c_i∑b​min(b)=∑i=0n−1​arr[i]⋅ci​

This is the contribution technique: each element adds its value once for every subarray it is the minimum of.

2. Counting the subarrays of one element

Fix an index iii. Let left[i] be the index of the nearest element to the left that is strictly smaller than arr[i], or −1-1−1 if there is none. Let right[i] be the index of the nearest element to the right that is smaller than or equal to arr[i], or nnn if there is none.

A subarray from index LLL to index RRR has arr[i] as its claimed minimum when it contains iii and stays between these two walls:

left[i]<L≤ii≤R<right[i]\text{left}[i] < L \le i \qquad i \le R < \text{right}[i]left[i]<L≤ii≤R<right[i]

LLL has i−left[i]i - \text{left}[i]i−left[i] choices, and RRR has right[i]−i\text{right}[i] - iright[i]−i choices. Every pair (L,R)(L, R)(L,R) gives a different subarray, so

ci=(i−left[i])⋅(right[i]−i)c_i = (i - \text{left}[i]) \cdot (\text{right}[i] - i)ci​=(i−left[i])⋅(right[i]−i)

3. Why the walls are right

Inside the walls, no element is smaller than arr[i]. So every subarray from LLL to RRR has minimum arr[i]. A subarray that reaches past left[i] contains a smaller element, so its minimum is not arr[i]. A subarray that reaches right[i] contains an element that is smaller or equal. When it is smaller, the minimum is not arr[i]. When it is equal, a later copy of the same value claims the subarray, as part 4 explains.

The code finds both walls in one pass with a stack of indices whose values increase from bottom to top. When arr[i] arrives, every index on top with a value greater than or equal to arr[i] is popped. For each popped index, arr[i] is the first value to its right that is smaller or equal, so the code sets its right to i. After the pops, the index on top, if any, holds a value strictly smaller than arr[i], so it is left[i].

4. Equal values: strict on one side only

When a subarray contains its minimum value twice, only one of the two indices may count it. The code is strict on the left side (left[i] is strictly smaller) and not strict on the right side (right[i] is smaller or equal). So the rightmost copy of the minimum claims the subarray.

Take arr = [2, 2]. Its three subarrays [2], [2] and [2, 2] have minimums that add up to 666. With the code's walls, index 0 gets right[0] = 1 and counts 1⋅1=11 \cdot 1 = 11⋅1=1 subarray. Index 1 gets left[1] = -1 and counts 2⋅1=22 \cdot 1 = 22⋅1=2 subarrays. The total is 2⋅1+2⋅2=62 \cdot 1 + 2 \cdot 2 = 62⋅1+2⋅2=6, which is correct.

If both walls allowed equal values to pass, both indices would count [2, 2], and the total would be 888. If both walls stopped at equal values, neither index would count [2, 2], and the total would be 444.

5. Example 1 by hand

arr = [3,1,2,4], so n=4n = 4n=4.

iiiarr[i]left[i]right[i]i−left[i]i - \text{left}[i]i−left[i]right[i]−i\text{right}[i] - iright[i]−icic_ici​arr[i]⋅ci\text{arr}[i] \cdot c_iarr[i]⋅ci​
03−1-1−111113
11−1-1−142366
22141224
34241114

The value 1 at index 1 is the minimum of 6 subarrays: LLL is 0 or 1, and RRR is 1, 2 or 3. The counts add up to 1+6+2+1=101 + 6 + 2 + 1 = 101+6+2+1=10, which is all 4⋅52=10\frac{4 \cdot 5}{2} = 1024⋅5​=10 subarrays. The sum is 3+6+4+4=173 + 6 + 4 + 4 = 173+6+4+4=17, the expected output.

6. Example 2 by hand

arr = [11,81,94,43,3], so n=5n = 5n=5.

iiiarr[i]left[i]right[i]cic_ici​arr[i]⋅ci\text{arr}[i] \cdot c_iarr[i]⋅ci​
011−1-1−141⋅4=41 \cdot 4 = 41⋅4=444
181031⋅2=21 \cdot 2 = 21⋅2=2162
294131⋅1=11 \cdot 1 = 11⋅1=194
343043⋅1=33 \cdot 1 = 33⋅1=3129
43−1-1−155⋅1=55 \cdot 1 = 55⋅1=515

The counts add up to 4+2+1+3+5=154 + 2 + 1 + 3 + 5 = 154+2+1+3+5=15 subarrays. The sum is 44+162+94+129+15=44444 + 162 + 94 + 129 + 15 = 44444+162+94+129+15=444. It is smaller than 109+710^9 + 7109+7, so the modulo leaves it unchanged, and the code returns 444, the expected output.

7. From the formulas to the code
FormulaIn sumSubarrayMins
nearest strictly smaller on the left, or −1-1−1left = [-1] * n and left[i] = stack[-1] if stack else -1
nearest smaller or equal on the right, or nnnright = [n] * n and right[stack.pop()] = i
pop while the top is greater than or equalwhile stack and arr[stack[-1]] >= arr[i]:
∑iarr[i]⋅(i−left[i])⋅(right[i]−i)\sum_i \text{arr}[i] \cdot (i - \text{left}[i]) \cdot (\text{right}[i] - i)∑i​arr[i]⋅(i−left[i])⋅(right[i]−i)sum(arr[i] * (i - left[i]) * (right[i] - i) for i in range(n))
the answer modulo 109+710^9 + 7109+7% MOD

Every index is pushed once and popped at most once, so the pass takes O(n)O(n)O(n) time. The arrays left and right and the stack take O(n)O(n)O(n) space.

Code Shape
Archetype Code Shape
Python
1for i in range(n):
2 while stack and arr[stack[-1]] >= arr[i]:
3 right[stack.pop()] = i
4 left[i] = stack[-1] if stack else -1
5 stack.append(i)
6total = sum(arr[i] * (i - left[i]) * (right[i] - i) for i in range(n))
7return total % (10**9 + 7)

Conceptual Narrative

Evaluating all O(N²) subarrays times out. Inverting the perspective—calculating how many subarrays each element serves as the minimum for—solves the problem in a single O(N) monotonic stack pass.

🧭 Conceptual Foundation & Pattern Intuition

A brute force calculates min⁡(A[i..j])\min(A[i..j])min(A[i..j]) for all O(N2)O(N^2)O(N2) subarrays, which is impossible for N=3⋅104N = 3 \cdot 10^4N=3⋅104. Instead of asking "what is the minimum of subarray [i..j][i..j][i..j]?", invert the question: "In how many subarrays is A[k] the minimum element?"\textbf{"In how many subarrays is } A[k] \textbf{ the minimum element?"}"In how many subarrays is A[k] the minimum element?" If A[k]A[k]A[k] is the minimum for CkC_kCk​ distinct subarrays, its total contribution to the answer is A[k]×CkA[k] \times C_kA[k]×Ck​. How do we calculate CkC_kCk​?

  • Find the Previous Less Element (PLE): the first index L<kL < kL<k where A[L]<A[k]A[L] < A[k]A[L]<A[k]. A[k]A[k]A[k] can extend k−Lk - Lk−L choices to the left.
  • Find the Next Less Element (NLE): the first index R>kR > kR>k where A[R]≤A[k]A[R] \le A[k]A[R]≤A[k]. A[k]A[k]A[k] can extend R−kR - kR−k choices to the right.
  • Total subarrays with A[k]A[k]A[k] as minimum: Ck=(k−L)×(R−k)C_k = (k - L) \times (R - k)Ck​=(k−L)×(R−k).
  • Asymmetric Tie-Breaking: To avoid double-counting subarrays when duplicate numbers exist (e.g. [2,2][2, 2][2,2]), use strict inequality (<<<) on one side and non-strict (≤\le≤) on the other!
👑 The Analogy: The King of the Valley Domain

Imagine each number in the array is a king ruling a valley. A king rules in both directions as long as the neighboring peaks are taller than him. His dominion to the left stops the moment he encounters a king strictly shorter than himself (LLL); his dominion to the right stops the moment he encounters a king shorter or equally tall (RRR). The number of subarrays in which he is the minimum is the product of his left expansion choices and his right expansion choices (k−L)×(R−k)(k - L) \times (R - k)(k−L)×(R−k).

🔑 Why It Works

One increasing stack gives both boundaries: an index popped by arr[i] gets right = i (the first smaller-or-equal value), and the index left under i is its previous strictly smaller value. Stopping at a strictly smaller value on the left and a smaller-or-equal value on the right gives every subarray exactly one minimum owner, so ties are never counted twice.

  • Double-counting duplicate values: Using strict inequalities on both left and right causes subarrays spanning identical minimums to be counted twice. Use < on left and <= on right.

  • Forgetting modulo arithmetic: Sum can grow astronomically; compute total = (total + nums[i] * left * right) % (10**9 + 7) on every addition.

  • Empty stack boundary off-by-one: When no smaller element exists to the left, distance is i−(−1)=i+1i - (-1) = i + 1i−(−1)=i+1. When no smaller element exists to the right, distance is n−in - in−i.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

The statement asks for the sum of min(b) over every contiguous subarray b, with arr.length up to 3 * 10^4: listing all O(N²) subarrays is too slow, so count each element's share instead (Contribution Technique).

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: arr[i] is the minimum of every subarray that starts in left[i] + 1 .. i and ends in i .. right[i] - 1, where left[i] is the previous strictly smaller index and right[i] the next smaller-or-equal index; the values at the indices in stack strictly increase from bottom to top.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Ties: pop while arr[stack[-1]] >= arr[i], so the right boundary is the next smaller-or-equal value and the left one the previous strictly smaller value. The same rule on both sides counts a tied subarray twice (< on both) or never (<= on both).

  • Modulo: the blueprint takes % MOD once, at the end, which is safe in Python; forgetting it returns a number above 10^9 + 7. In Java or C++, use 64-bit products and reduce on every addition.

  • Defaults: left starts at -1 and right at n, so an element with no smaller value on a side reaches the end of the array.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"This is the Contribution Technique. Listing all subarrays is O(n squared), so I flip the question: in how many subarrays is arr[i] the minimum? It stays the minimum until the first smaller value on each side, so with left[i] and right[i] as those boundaries it owns (i minus left[i]) times (right[i] minus i) subarrays. One increasing stack finds both in a single pass: when arr[i] pops an index, arr[i] is that index's right boundary, and whatever is left under i is its left boundary. The trap is ties: I pop on greater-or-equal, so the right side stops at an equal value and the left side only at a strictly smaller one, and each subarray is counted once. Then I sum value times share and take the modulo. Each index is pushed once and popped at most once: O(n) time, O(n) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the blueprint's two loops. The for i in range(n) loop pushes each index once with stack.append(i), and the inner while pops each index at most once (setting right[stack.pop()] = i), so across the whole loop there are at most N pushes and N pops: O(N) amortized, even though one step may pop many indices. left[i] = stack[-1] if stack else -1 is O(1) per step. The final sum(arr[i] * (i - left[i]) * (right[i] - i) for i in range(n)) does O(1) work per index: O(N). Total: O(N) + O(N) = O(N).

SPACE COMPLEXITY

O(N)

Look at the allocations: left and right hold N indices each, and stack holds at most N indices (on a strictly increasing array nothing is popped). The answer is one integer. Auxiliary space: O(N).

Formal Recurrence Relation

T(N)=2N⏟pushes + pops+N⏟sum=O(N)T(N) = \underbrace{2N}_{\text{pushes + pops}} + \underbrace{N}_{\text{sum}} = O(N)T(N)=pushes + pops2N​​+sumN​​=O(N)

Derivation Progression

One Pass Fills Both Boundaries

pushes=N,pops≤N\text{pushes} = N, \quad \text{pops} \le Npushes=N,pops≤N

When arr[i] pops an index, it becomes that index's right (the first smaller-or-equal value); the index left under i is left[i] (strictly smaller). Each index enters and leaves the stack at most once.

Share of Each Element

sharei=arr[i]⋅(i−left[i])⋅(right[i]−i)\text{share}_i = arr[i] \cdot (i - left[i]) \cdot (right[i] - i)sharei​=arr[i]⋅(i−left[i])⋅(right[i]−i)

O(1) per index: arr[i] is the minimum of every subarray starting in left[i] + 1 .. i and ending in i .. right[i] - 1.

Sum of Shares

Total=(∑i=0N−1sharei) mod (109+7)\text{Total} = \left(\sum_{i=0}^{N-1} \text{share}_i\right) \bmod (10^9 + 7)Total=(∑i=0N−1​sharei​)mod(109+7)

N more O(1) steps; Python takes the modulo once at the end.

Variable Definitions

NNN

Length of input array arr

Memory Architecture & Bounds

🟣 Call Stack

O(1) Non-recursive loops

🔵 Auxiliary Heap

O(N) For the left and right arrays and the monotonic stack

🟢 Output Space

O(1) One integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N) strictly increasing array: nothing is popped until the end.

Average Case

O(N)O(N)O(N).

Worst Case

O(N)O(N)O(N) strictly decreasing array: every index is popped by the next one.

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "sum of min(b) over all contiguous subarrays b", "modulo 109 + 7". Instead of iterating over all O(N2)O(N^2)O(N2) subarrays, invert the perspective: Contribution Counting. For each element arr[i]arr[i]arr[i], count the subarrays in which arr[i]arr[i]arr[i] is the minimum, ties going to one copy only.

CONSTRAINTS & BOUNDS

1≤arr.length≤3×1041 \le arr.length \le 3 \times 10^41≤arr.length≤3×104, 1≤arr[i]≤3×1041 \le arr[i] \le 3 \times 10^41≤arr[i]≤3×104. Time budget: O(N)O(N)O(N); the O(N2)O(N^2)O(N2) scan is about 4.5×1084.5 \times 10^84.5×108 subarrays. Modulo 109+710^9 + 7109+7.

FAANG PRODUCTION TRAPS & EDGE CASES

Overflow outside Python: one share arr[i]×(i−left[i])×(right[i]−i)arr[i] \times (i - left[i]) \times (right[i] - i)arr[i]×(i−left[i])×(right[i]−i) can reach about 3×104×1.5×104×1.5×104≈6.75×10123 \times 10^4 \times 1.5 \times 10^4 \times 1.5 \times 10^4 \approx 6.75 \times 10^{12}3×104×1.5×104×1.5×104≈6.75×1012, far past 32 bits, so Java and C++ need 64-bit products and a modulo on every addition; Python can reduce once at the end. On a stream, right is only known when a later value pops the index, so a share can be added only once its right boundary has arrived.

Core Algorithmic State Invariants

  1. Every Subarray Has Exactly One Owner

Take any subarray and its smallest value; if that value appears more than once, the rightmost copy owns it: its range stops at the first smaller-or-equal value on the right, so it reaches the end of the subarray, and at a strictly smaller value on the left, so it reaches the start. Every other copy's range stops at the next equal value. So each subarray is added exactly once.

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•