Maximum-Dominated Subarray Spans
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given an integer list nums of length n and a boolean flag circular, implement compute_subarray_spans(nums, circular) to return an integer list spans of length n.
For each position i (0 <= i < n), spans[i] is the length of the longest contiguous segment containing index i whose largest element equals nums[i]:
- Every element inside a valid segment must satisfy
nums[k] <= nums[i]. Values equal tonums[i]are permitted, whereas any value strictly larger thannums[i]cannot be included. - When
circularisFalse, segments are ordinary non-wrapping slicesnums[l..r]with0 <= l <= i <= r < n. - When
circularisTrue, the array forms a ring in which index0immediately follows indexn - 1. A circular segment of lengthL(1 <= L <= n) starts at some indexsand covers indicess, (s + 1) % n, ..., (s + L - 1) % nwithout visiting any index more than once. - When
numsis empty, return[].
Examples
Example 1
Input: nums = [3, 7, 5, 5, 2, 8], circular = False
Output: [1, 5, 3, 3, 1, 6]
i = 0(3): stopped on the right by7at index1->[3](length1).i = 1(7): covers indices0..4([3, 7, 5, 5, 2]) before hitting8at index5(length5).i = 2, 3(5): equal neighbors do not block each other, so both share[5, 5, 2]across indices2..4(length3).i = 4(2): trapped between5and8->[2](length1).i = 5(8): covers the entire array[3, 7, 5, 5, 2, 8](length6).
Example 2
Input: nums = [4, 6, 2, 5, 4], circular = False
Output: [1, 5, 1, 3, 1]
Without wrap-around, nums[0] = 4 stops at index 0 and nums[4] = 4 stops at index 4 (nums[3] = 5 > 4), while nums[3] = 5 spans [2, 5, 4] (length 3).
Example 3
Input: nums = [4, 6, 2, 5, 4], circular = True
Output: [2, 5, 1, 4, 2]
With wrap-around enabled, nums[4] = 4 and nums[0] = 4 join across the boundary into [4, 4] (length 2), and nums[3] = 5 reaches across indices 2, 3, 4, 0 ([2, 5, 4, 4], length 4) before stopping at nums[1] = 6 on both ends.
Example 4
Input: nums = [-2, -5, -1, -3], circular = True
Output: [3, 1, 4, 1]
-1 at index 2 is the largest value overall and spans all 4 elements, while -2 at index 0 wraps left to include -3 at index 3 and right to include -5 at index 1 ([-3, -2, -5], length 3).
Constraints
0 <= len(nums) <= 2 * 10^5-10^9 <= nums[i] <= 10^9circularisFalseorTrue.
Step-by-step walkthrough
Understand what stops a valid segment
For each index
i, we want the longest contiguous segment containingiwhose maximum value equalsnums[i].Because index
iitself belongs to the segment,nums[i]is already inside. Therefore, the segment's maximum equalsnums[i]if and only if no element in the segment is strictly larger thannums[i]:- Neighbors smaller than
nums[i]are allowed. - Neighbors equal to
nums[i]are also allowed—they keep the maximum equal tonums[i]. - Only a neighbor strictly greater (
> nums[i]) acts as a blocking wall that we cannot step onto.
We must support both modes for
nup to2 * 10^5: -circular = False: ordinary slicesnums[l..r]bounded by0andn - 1. -circular = True: index0follows indexn - 1, so segments can wrap across the boundary (up to lengthn).- Neighbors smaller than
Turn each span into two wall indices
Start with
circular = False. Standing at indexiand expanding outward in both directions, where must you stop?- On the left, you stop right before
prev_greater[i]: the nearest indexj < iwithnums[j] > nums[i](or-1if no taller element appears to the left). - On the right, you stop right before
next_greater[i]: the nearest indexj > iwithnums[j] > nums[i](ornif no taller element appears to the right).
Look at
i = 1(nums[1] = 7) in Example 1,nums = [3, 7, 5, 5, 2, 8]:index: -1 0 1 2 3 4 5 6 value: (wall) 3 7 5 5 2 8 (wall) ▲ └────┴────┴────┴────┘ ▲ prev_greater[1] = -1 next_greater[1] = 5 (since 8 > 7) Valid inclusive indices: 0, 1, 2, 3, 4 -> length = 5 - (-1) - 1 = 5Because both
prev_greater[i]andnext_greater[i]are exclusive wall positions just outside the valid window(prev_greater[i] + 1) .. (next_greater[i] - 1), the window length is always:spans[i] = next_greater[i] - prev_greater[i] - 1Walking outward from every index
iindividually would work on small inputs, but onnums = [5, 5, ..., 5]every single index scans the entire array—takingO(n^2)(4 * 10^10steps forn = 2 * 10^5). We needprev_greaterandnext_greaterfor all indices inO(n)total time.- On the left, you stop right before
Find nearest strictly greater neighbors with a monotonic stack
As we scan
ifrom0ton - 1, which earlier indices could ever serve asprev_greaterforior for some future element afteri?Suppose an earlier index
j < ihasnums[j] <= nums[i]: 1.nums[j]is not strictly greater thannums[i], sojcannot blocki. 2. Even better,jcan never be the nearest strictly greater blocker for any later indexk > ieither! Why? Becauseisits closer tokthanjdoes, andnums[i] >= nums[j]—so whenevernums[j] > nums[k],nums[i] > nums[k]is already true first.This lets us maintain a monotonic stack (a stack whose stored elements stay sorted—here, indices whose values strictly decrease from bottom to top):
- While the stack is non-empty and
nums[stack[-1]] <= nums[i], pop that useless index off the top. (Note<=, not<: equal elements do not blocknums[i], so they must be popped!) - After popping, if the stack is non-empty, its top index is guaranteed to be the nearest index to the left with a value strictly greater than
nums[i]—recordprev_greater[i] = stack[-1]. - Push
ionto the stack so it can act as a wall for future smaller elements.
Watch the stack find
prev_greateron Example 1,nums = [3, 7, 5, 5, 2, 8]:i=0 (val 3): pop nothing -> prev_greater[0] = -1, push 0 -> stack=[0(val 3)] i=1 (val 7): pop 0 (3 <= 7) -> prev_greater[1] = -1, push 1 -> stack=[1(val 7)] i=2 (val 5): top is 1 (7 > 5) -> prev_greater[2] = 1, push 2 -> stack=[1(7), 2(5)] i=3 (val 5): pop 2 (5 <= 5), top 1 -> prev_greater[3] = 1, push 3 -> stack=[1(7), 3(5)] i=4 (val 2): top is 3 (5 > 2) -> prev_greater[4] = 3, push 4 -> stack=[1(7), 3(5), 4(2)] i=5 (val 8): pop 4, 3, 1 (<= 8) -> prev_greater[5] = -1, push 5 -> stack=[5(val 8)]Running the exact same logic from right to left (
n - 1down to0) givesnext_greater[i]. Every index is pushed once and popped at most once per pass, so each pass runs inO(n)time!- While the stack is non-empty and
Code the linear span helper
def linear_spans(nums: List[int]) -> List[int]: """Return max subarray lengths around each index i with no value > nums[i].""" n = len(nums) # prev_greater[i]: index of nearest element to the left with nums[j] > nums[i], # or -1 when no strictly greater element exists to the left. prev_greater = [-1] * n # decreasing_stack: indices [j0, j1, ...] whose values strictly decrease # from bottom to top (nums[j0] > nums[j1] > ...). decreasing_stack: List[int] = [] for i in range(n): # Use <= (not <): equal values do NOT block nums[i]'s window, and index i # is both >= nums[j] and closer for any future element to the right. while decreasing_stack and nums[decreasing_stack[-1]] <= nums[i]: decreasing_stack.pop() if decreasing_stack: prev_greater[i] = decreasing_stack[-1] decreasing_stack.append(i) # next_greater[i]: index of nearest element to the right with nums[j] > nums[i], # or n when no strictly greater element exists to the right. next_greater = [n] * n decreasing_stack = [] for i in range(n - 1, -1, -1): while decreasing_stack and nums[decreasing_stack[-1]] <= nums[i]: decreasing_stack.pop() if decreasing_stack: next_greater[i] = decreasing_stack[-1] decreasing_stack.append(i) # Both prev_greater[i] and next_greater[i] are exclusive blocking walls, # so the valid window runs from (prev_greater[i] + 1) to (next_greater[i] - 1). spans = [0] * n for i in range(n): spans[i] = next_greater[i] - prev_greater[i] - 1 return spansHandle the circular case by cutting the circle at its maximum
In circular mode, a segment can wrap from
n - 1into0—unless something blocks it. Can we cut the circle at a place where no segment ever needs to wrap across the cut?Pick the largest value
max_val = max(nums)at indexmax_idx, and rotate the array sorotated[0] == max_val:Example 3: nums = [4, 6, 2, 5, 4] (max_val = 6 at max_idx = 1) nums[0]=4 ── nums[1]=6 │ │ Cut right before index 1 (val 6) and unroll: nums[4]=4 │ rotated = [ 6 | 2, 5, 4, 4 ] (next on circle: 6!) \ / p=0 p=1 p=2 p=3 p=4 nums[3]=5 ── nums[2]=2Check both kinds of elements in
rotated: 1. Elements strictly smaller thanmax_val(like2,5, and4): Their valid circular segment can never includemax_val. Inrotated,rotated[0] = max_valsits at the left end, AND on the circlerotated[0]is also the element immediately afterrotated[n - 1]! So a smaller element stops at or beforep = 0going left, and stops at or beforep = n(right beforerotated[0]) going right. No valid segment ever wraps across the cut! 2. Elements equal tomax_val(like6): Nothing in the circle is strictly greater, so their circular span isn. Inlinear_spans(rotated), they haveprev_greater = -1andnext_greater = n, givingn - (-1) - 1 = nas well!Thus
linear_spans(rotated)computes the exact circular spans! We simply copy eachrotated_spans[p]back to its original index(max_idx + p) % n.Code the circular helper and main function
def circular_spans(nums: List[int]) -> List[int]: """Return max circular segment lengths around each index i with no value > nums[i].""" n = len(nums) if n == 0: return [] # Rotate so a global maximum sits at rotated[0]. On the circle, rotated[0] # sits both at the left edge and immediately after rotated[n - 1], so no # smaller value can ever wrap across that boundary, while every copy of the # global maximum spans all n elements. max_val = max(nums) max_idx = nums.index(max_val) rotated = nums[max_idx:] + nums[:max_idx] rotated_spans = linear_spans(rotated) # Map each rotated position p back to its original index (max_idx + p) % n. ans = [0] * n for p in range(n): original_idx = (max_idx + p) % n ans[original_idx] = rotated_spans[p] return ans def compute_subarray_spans(nums: List[int], circular: bool) -> List[int]: if circular: return circular_spans(nums) return linear_spans(nums)Trace Example 3 end to end
Let's trace
nums = [4, 6, 2, 5, 4]withcircular = True:1. Find global maximum: max_val = 6 at max_idx = 1 2. Rotate to start at index 1: rotated = [6, 2, 5, 4, 4] 3. Run linear_spans([6, 2, 5, 4, 4]): p rotated[p] prev_greater next_greater span = next - prev - 1 0 6 -1 5 5 - (-1) - 1 = 5 1 2 0 2 2 - 0 - 1 = 1 2 5 0 5 5 - 0 - 1 = 4 3 4 2 5 5 - 2 - 1 = 2 4 4 2 5 5 - 2 - 1 = 2 (At p=4, value 4 pops p=3's equal 4 from the stack, so both 4s share prev_greater = 2 and next_greater = 5, while p=2's 5 spans [2, 5, 4, 4]!) 4. Unrotate back via original_idx = (1 + p) % 5: p=0 (span 5) -> ans[1] = 5 p=1 (span 1) -> ans[2] = 1 p=2 (span 4) -> ans[3] = 4 p=3 (span 2) -> ans[4] = 2 p=4 (span 2) -> ans[0] = 2 Final result: ans = [2, 5, 1, 4, 2]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def linear_spans(nums: List[int]) -> List[int]: """Return max subarray lengths around each index i with no value > nums[i].""" n = len(nums) # prev_greater[i]: index of nearest element to the left with nums[j] > nums[i], # or -1 when no strictly greater element exists to the left. prev_greater = [-1] * n # decreasing_stack: indices [j0, j1, ...] whose values strictly decrease # from bottom to top (nums[j0] > nums[j1] > ...). decreasing_stack: List[int] = [] for i in range(n): # Use <= (not <): equal values do NOT block nums[i]'s window, and index i # is both >= nums[j] and closer for any future element to the right. while decreasing_stack and nums[decreasing_stack[-1]] <= nums[i]: decreasing_stack.pop() if decreasing_stack: prev_greater[i] = decreasing_stack[-1] decreasing_stack.append(i) # next_greater[i]: index of nearest element to the right with nums[j] > nums[i], # or n when no strictly greater element exists to the right. next_greater = [n] * n decreasing_stack = [] for i in range(n - 1, -1, -1): while decreasing_stack and nums[decreasing_stack[-1]] <= nums[i]: decreasing_stack.pop() if decreasing_stack: next_greater[i] = decreasing_stack[-1] decreasing_stack.append(i) # Both prev_greater[i] and next_greater[i] are exclusive blocking walls, # so the valid window runs from (prev_greater[i] + 1) to (next_greater[i] - 1). spans = [0] * n for i in range(n): spans[i] = next_greater[i] - prev_greater[i] - 1 return spans def circular_spans(nums: List[int]) -> List[int]: """Return max circular segment lengths around each index i with no value > nums[i].""" n = len(nums) if n == 0: return [] # Rotate so a global maximum sits at rotated[0]. On the circle, rotated[0] # sits both at the left edge and immediately after rotated[n - 1], so no # smaller value can ever wrap across that boundary, while every copy of the # global maximum spans all n elements. max_val = max(nums) max_idx = nums.index(max_val) rotated = nums[max_idx:] + nums[:max_idx] rotated_spans = linear_spans(rotated) # Map each rotated position p back to its original index (max_idx + p) % n. ans = [0] * n for p in range(n): original_idx = (max_idx + p) % n ans[original_idx] = rotated_spans[p] return ans def compute_subarray_spans(nums: List[int], circular: bool) -> List[int]: if circular: return circular_spans(nums) return linear_spans(nums)✅ Submit now — all tests should pass.
Intuition & how it works
Picture each number nums[i] as the height of a rooftop, and imagine standing on rooftop i looking left and right through a level telescope. Your line of sight passes freely over rooftops that are shorter or the exact same height, and stops only when it hits a strictly taller building (or the edge of town). The longest valid segment around i is simply every rooftop strictly between the first taller building on the left (prev_greater[i]) and the first taller building on the right (next_greater[i]). Using sentinel indices (dummy boundary positions -1 before index 0 and n after index n - 1 when no taller building exists), that span is always next_greater[i] - prev_greater[i] - 1.
Why does the obvious outward-walk approach fail? If you walk left and right separately from every index, an array of identical values like [5, 5, ..., 5] forces every single index to scan all n elements. For n = 200,000, that takes roughly n^2 = 4 * 10^10 comparisons and times out.
Instead, we sweep once left-to-right and once right-to-left with a monotonic stack (a stack that keeps its stored indices sorted by strictly decreasing height from bottom to top, popping any shorter or equal height before pushing the current index). For the circular version, we first rotate the array so its global maximum sits at index 0: because no smaller value can ever include the global maximum, no valid segment ever wraps across index 0, reducing the circular problem directly to one linear sweep!
Walk through Example 3, nums = [4, 6, 2, 5, 4] in circular mode:
1. The largest value 6 sits at index 1, so we rotate to rotated = [6, 2, 5, 4, 4].
2. Left-to-right sweep for prev_greater: p = 0 (6) sees empty stack (-1); p = 1 (2) sees 0; p = 2 (5) pops p = 1 and sees 0; p = 3 (4) sees 2; p = 4 (4) pops p = 3 (4 <= 4) and also sees 2. Thus prev_greater = [-1, 0, 0, 2, 2].
3. Right-to-left sweep for next_greater: only p = 1 (2) has a taller element to its right (p = 2, value 5), giving next_greater = [5, 2, 5, 5, 5].
4. Subtracting next_greater - prev_greater - 1 gives rotated_spans = [5, 1, 4, 2, 2], and placing each span back at (1 + p) % 5 produces [2, 5, 1, 4, 2].
Complexity
- Time — O(n) in both linear and circular modes: Each of the two stack passes visits
nindices. Although there is awhileloop inside theforloop, each index is pushed ontodecreasing_stackonce and popped at most once, making the stack work amortized O(1) per element (averaging out to constant work per step, at most2nstack operations per pass). Circular mode adds findingmax(nums), slicingrotated, and mapping indices back, each taking oneO(n)pass. - Space — O(n): Storing
prev_greater,next_greater,decreasing_stack, and the output list (plusrotatedin circular mode) each use at mostnintegers.
Edge cases
- Empty array (
nums = []): Returns[]in both modes (circular_spansreturns early before callingmax([])). - Single element (
nums = [7]):prev_greater = [-1]andnext_greater = [1], giving[1]in both modes. - All equal elements (
nums = [3, 3, 3]): Because<=pops equal elements off the stack, no element blocks another and every index gets spann([3, 3, 3]). - Equal elements split by a larger peak (
nums = [4, 6, 2, 5, 4]): Linearly each outer4is isolated (1), whereas circularly both4s join around the boundary (2) and5reaches across both (4). - Multiple copies of the global maximum in circular mode (
[1, 4, 2, 4, 3]): Rotating to the first4givesrotated = [4, 2, 4, 3, 1], where both4s still haveprev_greater = -1andnext_greater = 5, so every copy of the global maximum rightly gets spann = 5. - Negative integers (
[-2, -5, -1, -3]): Only relative<=comparisons are performed, so negative numbers behave identically to positive ones (-1is the maximum and spans all4items).
Common mistakes
- Using
<instead of<=in the stackwhileloop: If you only pop strictly smaller elements (nums[stack[-1]] < nums[i]), equal neighbors stay on the stack and act like walls—turning[3, 3, 3]into[1, 1, 1]instead of[3, 3, 3]. - Off-by-one error in the span formula: Since
prev_greater[i]andnext_greater[i]are the excluded wall indices themselves, the count of elements strictly between them isnext_greater[i] - prev_greater[i] - 1(notnext_greater[i] - prev_greater[i]). - Doubling the array
nums + numswithout capping atn: If you runlinear_spans(nums + nums)directly, the global maximum spans all2nelements of the doubled array instead ofn, and smaller elements near the seam can get truncated if read from the wrong copy. Rotating tomax(nums)avoids both pitfalls cleanly. - Rotating to an arbitrary index instead of the global maximum: Cutting the circle anywhere except at
max(nums)slices right through segments of larger elements that genuinely wrap across that cut.
Alternative approaches
- Insert blockers from largest to smallest (
O(n log n)): Group indices by value and process groups in strictly decreasing order, maintaining a balanced binary search tree (a sorted data structure supportingO(log n)insertion and predecessor/successor queries) of already-processed indices. When processing valuev, the tree contains every index with value> v, so binary-searchingi's neighbors immediately givesprev_greater[i]andnext_greater[i]. Because Python's standard library lacks a balanced search tree and the monotonic stack runs inO(n)time, the stack is both faster and shorter to write. - Two-pass scan over
2nvirtual indices for circular mode (O(n)without rotating): You can scankfrom0to2n - 1readingnums[k % n]to find each index's circular distance to the next strictly greater element on the right and on the left, capping atnwhen no greater element exists. Rotation achieves the sameO(n)bound while reusinglinear_spansunchanged.
Follow-up questions
- How does the algorithm change if nums[i] must be the strictly unique maximum of the segment (no ties allowed)? Equal values now disqualify a subarray, so equal neighbors act as blocking walls too. In the linear case, change both
whileconditions from<=to<(nums[decreasing_stack[-1]] < nums[i]) so equal elements remain on the stack and stop the window. In the circular case, note one subtlety: when the global maximum appears more than once (say[5, 1, 5, 1]),rotated[0] = 5can wrap left across trailing< 5elements up to the last5, so scanning2nvirtual indices (k % n) with<handles both unique and tied global maximums uniformly inO(n)time. - How could you adapt this monotonic-stack idea to count how many subarrays have nums[i] as their maximum? Any subarray
[l..r]whose leftmost maximum sits atimust start after the nearest element>= nums[i]on the left (left_ge[i] < l <= i) and end before the nearest element> nums[i]on the right (i <= r < right_gt[i]). Using<on the left pass (so ties stop at the earlier copy) and<=on the right pass credits every subarray once to its leftmost maximum, giving(i - left_ge[i]) * (right_gt[i] - i)subarrays for indexi. - If array elements arrive one at a time in a data stream, how soon can each element's span be finalized?
prev_greater[i]is known immediately on arrival because the left-to-right monotonic stack is already online (processing each incoming item without looking ahead). By contrast,next_greater[i]cannot be finalized until a strictly greater value> nums[i]eventually arrives in the stream (or the stream closes), at which moment poppingifrom the active stack revealsnext_greater[i]on the fly.
Follow-up questions
- How does the algorithm change if nums[i] must be the strictly unique maximum of the segment (no ties allowed)?
- How could you adapt this monotonic-stack idea to count how many subarrays have nums[i] as their maximum?
- If array elements arrive one at a time in a data stream, how soon can each element's span be finalized?
Similar questions
- Room Key Reachability and Balanced Parentheses Score
- Range Sum Queries with Point Updates
- Design Search Autocomplete
- Daily Top Spenders and Post-Launch Cost per KPI
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger