Subarray Ranges Interview: Assign Equal Values to One Side Before Counting Contributions
Quick Overview
Contribution counting needs one owner for an extremum shared by equal values. Pair a strict boundary with a non-strict boundary, then verify both sums against an enumerated negative-and-duplicate example.
Equal values need a consistent ownership rule when you count subarray extrema by contribution. Pair a strict boundary on one side with a non-strict boundary on the other. Otherwise, two equal indices can both claim the same subarray, or neither can claim it.
Start with Sum Every Subarray's Maximum-Minus-Minimum and enumerate a short array containing both duplicates and a negative value. PracHub publishes this original rehearsal; linked questions provide adjacent practice rather than evidence of a company's assessment.
Official problem and Python references were checked on November 28, 2026. Our authored control compared stack contributions with direct enumeration for 1,092 bounded arrays and retained a per-index ledger for [-1,2,2]. Direct LeetCode HTTP access returned 403; its official description was successfully read through the web reader. No hidden judge or runtime benchmark is claimed.

Enumerate all six indexed subarrays
The official problem defines each nonempty contiguous subarray's range as its maximum minus its minimum, then asks for the total. The linear-time follow-up motivates contribution counting.
Our original example is [-1,2,2]. The repeated twos expose tie handling, while minus one prevents a positivity assumption from going unnoticed.
| Included indices | Subarray | Range |
|---|---|---|
| 0 through 0 | [-1] | 0 |
| 0 through 1 | [-1,2] | 3 |
| 0 through 2 | [-1,2,2] | 3 |
| 1 through 1 | [2] | 0 |
| 1 through 2 | [2,2] | 0 |
| 2 through 2 | [2] | 0 |
The sum is six. Both copies of the singleton two appear because they occupy different index ranges. The equal pair contributes zero range, but its maximum and minimum still need exactly one owner in their separate contribution sums.
This table is the initial oracle. A fast implementation that returns a different total must explain which indexed subarray was lost or counted incorrectly, rather than appealing to a familiar-looking stack template.
Separate the maximum sum from the minimum sum
For every subarray, range is maximum minus minimum. Summing allows us to compute the sum of all subarray maxima and subtract the sum of all subarray minima.
For an index i with value x, choose the subarrays for which that index is the designated extremum owner. If the nearest blocking boundaries are L and R, the number of choices is:
(i - L) * (R - i)
The left endpoint can be any position after L through i, and the right endpoint can be i through the position before R. Multiplying these independent choices counts the subarrays containing i within those boundaries.
Use virtual boundaries minus one and n when there is no blocking index. These are positions outside the array, not values that need to be smaller or larger than every input.
The contribution is x times that count. Negative x is permitted: the maximum sum and minimum sum can include negative terms even though each final range is nonnegative.
The bounded exhaustive domain also includes the singleton [-1]. Its maximum contribution and minimum contribution are both minus one, and their difference is zero. Clamping either component sum to zero independently would change the calculation rather than enforce the range definition. Preserve signed contributions until the two complete sums are subtracted; only the final per-subarray range has the nonnegative guarantee.
Give equal maxima to the rightmost index
Our convention designates the rightmost occurrence among equal extrema. For a maximum at i, use the previous strictly greater value as L and the next greater-or-equal value as R.
The strict previous boundary allows equal values on the left to belong to i's span. The non-strict next boundary stops i before a later equal value that should take ownership instead.
At index one, value two has no previous strictly greater element, so L is minus one. Its next greater-or-equal element is the two at index two. The left span is two and the right span one, giving two owned subarrays and contribution four.
At index two, there is still no previous strictly greater value, and no next blocker. Its spans are three and one, giving three owned subarrays and contribution six. These include the full array and the equal pair.
Index zero owns only its singleton as a maximum, contributing minus one. The maximum contribution sum is therefore minus one plus four plus six, or nine.
This is one valid convention. Mirroring the strict and non-strict choices can designate leftmost equal owners instead. The requirement is a consistent unique owner within each extremum calculation, not a universal preference for the rightmost index.
Apply the corresponding minimum boundaries
For minima under the same rightmost convention, use the previous strictly smaller value and the next smaller-or-equal value.
The minus one at index zero owns all three subarrays starting there as a minimum. Its contribution is minus three. Index one owns only its singleton two, contributing two; index two owns its singleton and the equal pair, contributing four.
The complete executed ledger is:
| Index | Value | Maximum contribution | Minimum contribution |
|---|---|---|---|
| 0 | -1 | -1 | -3 |
| 1 | 2 | 4 | 2 |
| 2 | 2 | 6 | 4 |
The maximum sum is nine and the minimum sum three. Subtracting gives six, matching the direct enumeration.
The ownership counts also total six in each pass: one plus two plus three for maxima, and three plus one plus two for minima. That is a useful check that the six indexed subarrays each received one owner, independently of their numeric contributions.
Expose double counting with strict boundaries on both sides
Our comparison control also calculated maximum contributions using strictly greater blockers on both sides. It produced thirteen rather than nine.
Under that rule, both twos can claim the subarray at indices one through two and the full array at zero through two. Each duplicate claim adds another two, accounting for the extra four in the maximum sum.
This explains the failure more precisely than saying the comparison operator is wrong. The equality decision assigned the same indexed subarray to two owners.
A non-strict comparison on both sides creates the opposite ownership risk for equal values: each can block the other from claiming a shared span. That is a proposed variation to test, not another numeric result measured by our strict-both-sides control.
Choose one owner for each shared span before implementing the stack. A perfectly maintained stack can compute the wrong boundary definition very efficiently.

Let the stack reveal each right boundary
For maxima, maintain indices with strictly decreasing values. When the current value is greater than or equal to the stack top's value, the current index becomes that popped index's next greater-or-equal boundary.
After popping i, the new stack top is its previous strictly greater boundary. The two spans are then available together, so the contribution can be added immediately.
For minima, reverse the value ordering and pop when the current value is smaller than or equal to the top. Equality still belongs to the new, rightmost index under our convention.
The tested helper uses this pattern:
for right in range(len(nums) + 1):
while stack and (
right == len(nums) or
(nums[stack[-1]] <= nums[right] if maximum
else nums[stack[-1]] >= nums[right])
):
i = stack.pop()
left = stack[-1] if stack else -1
total += nums[i] * (i - left) * (right - i)
stack.append(right)
Initialize stack and total separately, and return total after the loop. The complete retained source calls the helper for maxima and minima, then subtracts the two sums.
The final iteration uses index n to flush remaining entries. Short-circuit evaluation checks that terminal index before reading nums[right]. It does not require inventing a numeric sentinel outside the input domain.
Explain the operation bound and arithmetic width
Each real index is pushed once and popped once in a pass. The nested while loop therefore performs a linear number of stack operations across the entire traversal, rather than a fresh full scan for each index.
Python's list-as-stack documentation describes the append and end-pop operations used here. The stack can grow linearly with input length, so the auxiliary storage bound is linear as well.
Arithmetic width is a separate concern when translating the implementation. Under the official bounds of at most one thousand elements with magnitudes up to one billion, a simple upper bound on the total is 500,500 subarrays times two billion, or 1,001,000,000,000,000.
That is a conservative arithmetic bound, not a claim that every subarray can simultaneously attain the maximum range. It already exceeds a signed 32-bit total, so choose a sufficiently wide signed intermediate and widen before multiplication in a fixed-width implementation.
Python's numeric-type reference documents its integer behavior. Our Python control does not test overflow in a separate fixed-width translation or establish a byte-level memory estimate.
Compare independent calculations on a bounded domain
The direct oracle enumerates nonempty subarrays and scans each for its maximum and minimum. It does not share the optimized stack's ownership boundaries.
The control compared that oracle with the two-pass stack total for every array of lengths one through six over the values minus one, zero and two. There are 1,092 such arrays, and all totals matched.
That finite domain includes repeated extrema, all-equal arrays, negative entries and mixed orderings. It does not cover every integer magnitude, every larger length or the behavior of another programming language's arithmetic.
The oracle's repeated slicing and scanning are deliberately suitable only for small checks. Agreement with it is corroborating evidence, not a benchmark or a claim that the oracle itself is the linear solution.
For a proposed production regression, add the largest permitted magnitudes and a fixed-width accumulator test if the target language needs one. Preserve the tiny ledger too: it explains equality ownership more clearly than a large random failure case.
Defend the equality rule before shortening the code
A concise explanation starts with the six enumerated subarrays, then shows maximum sum nine and minimum sum three. Identify the rightmost two as the owner of shared equal-valued spans.
When challenged about strictness, show the strict-both-sides maximum sum thirteen and name the two duplicated subarrays. That is a concrete reason for the asymmetric boundary comparisons.
Finally, connect the stack pop condition to those boundaries. If an implementation uses another valid ownership convention, derive its comparisons from that convention rather than mechanically replacing operators until sample tests pass.
Practise the ledger in Sum Every Subarray's Maximum-Minus-Minimum before moving to histogram or window-minimum variants. Those problems share boundary techniques but optimize different quantities, so their equality rules deserve their own explanation.
Related PracHub practice
| PracHub question | What to practise |
|---|---|
| Sum Every Subarray's Maximum-Minus-Minimum | Separate maximum and minimum contributions before subtracting. |
| Sum the Minimum Value of Every Contiguous Subarray | Apply a consistent ownership rule to equal minima. |
| Largest Rectangle in a Histogram | Explain stack-pop boundaries through a concrete bar interval. |
| Count Segments Whose Exact Minimum and Maximum Match Two Bounds | Compare extremum ownership with fixed-bound endpoint counting. |
| Maximum of Fixed-Window Minimums | Distinguish per-window minima from all-subarray contributions. |
Use the extrema and histogram questions to rehearse interval ownership. The fixed-bound and window questions provide comparisons; they do not reuse this all-subarray contribution formula unchanged.
Comments (0)