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 to nums[i] are permitted, whereas any value strictly larger than nums[i] cannot be included.
  • When circular is False, segments are ordinary non-wrapping slices nums[l..r] with 0 <= l <= i <= r < n.
  • When circular is True, the array forms a ring in which index 0 immediately follows index n - 1. A circular segment of length L (1 <= L <= n) starts at some index s and covers indices s, (s + 1) % n, ..., (s + L - 1) % n without visiting any index more than once.
  • When nums is 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 by 7 at index 1 -> [3] (length 1).
  • i = 1 (7): covers indices 0..4 ([3, 7, 5, 5, 2]) before hitting 8 at index 5 (length 5).
  • i = 2, 3 (5): equal neighbors do not block each other, so both share [5, 5, 2] across indices 2..4 (length 3).
  • i = 4 (2): trapped between 5 and 8 -> [2] (length 1).
  • i = 5 (8): covers the entire array [3, 7, 5, 5, 2, 8] (length 6).

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^9
  • circular is False or True.

Step-by-step walkthrough

  1. Understand what stops a valid segment

    For each index i, we want the longest contiguous segment containing i whose maximum value equals nums[i].

    Because index i itself belongs to the segment, nums[i] is already inside. Therefore, the segment's maximum equals nums[i] if and only if no element in the segment is strictly larger than nums[i]:

    • Neighbors smaller than nums[i] are allowed.
    • Neighbors equal to nums[i] are also allowed—they keep the maximum equal to nums[i].
    • Only a neighbor strictly greater (> nums[i]) acts as a blocking wall that we cannot step onto.

    We must support both modes for n up to 2 * 10^5: - circular = False: ordinary slices nums[l..r] bounded by 0 and n - 1. - circular = True: index 0 follows index n - 1, so segments can wrap across the boundary (up to length n).

  2. Turn each span into two wall indices

    Start with circular = False. Standing at index i and expanding outward in both directions, where must you stop?

    • On the left, you stop right before prev_greater[i]: the nearest index j < i with nums[j] > nums[i] (or -1 if no taller element appears to the left).
    • On the right, you stop right before next_greater[i]: the nearest index j > i with nums[j] > nums[i] (or n if 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 = 5
    

    Because both prev_greater[i] and next_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] - 1
    

    Walking outward from every index i individually would work on small inputs, but on nums = [5, 5, ..., 5] every single index scans the entire array—taking O(n^2) (4 * 10^10 steps for n = 2 * 10^5). We need prev_greater and next_greater for all indices in O(n) total time.

  3. Find nearest strictly greater neighbors with a monotonic stack

    As we scan i from 0 to n - 1, which earlier indices could ever serve as prev_greater for i or for some future element after i?

    Suppose an earlier index j < i has nums[j] <= nums[i]: 1. nums[j] is not strictly greater than nums[i], so j cannot block i. 2. Even better, j can never be the nearest strictly greater blocker for any later index k > i either! Why? Because i sits closer to k than j does, and nums[i] >= nums[j]—so whenever nums[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):

    1. 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 block nums[i], so they must be popped!)
    2. 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]—record prev_greater[i] = stack[-1].
    3. Push i onto the stack so it can act as a wall for future smaller elements.

    Watch the stack find prev_greater on 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 - 1 down to 0) gives next_greater[i]. Every index is pushed once and popped at most once per pass, so each pass runs in O(n) time!

  4. 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 spans
    
  5. Handle the circular case by cutting the circle at its maximum

    In circular mode, a segment can wrap from n - 1 into 0—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 index max_idx, and rotate the array so rotated[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]=2
    

    Check both kinds of elements in rotated: 1. Elements strictly smaller than max_val (like 2, 5, and 4): Their valid circular segment can never include max_val. In rotated, rotated[0] = max_val sits at the left end, AND on the circle rotated[0] is also the element immediately after rotated[n - 1]! So a smaller element stops at or before p = 0 going left, and stops at or before p = n (right before rotated[0]) going right. No valid segment ever wraps across the cut! 2. Elements equal to max_val (like 6): Nothing in the circle is strictly greater, so their circular span is n. In linear_spans(rotated), they have prev_greater = -1 and next_greater = n, giving n - (-1) - 1 = n as well!

    Thus linear_spans(rotated) computes the exact circular spans! We simply copy each rotated_spans[p] back to its original index (max_idx + p) % n.

  6. 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)
    
  7. Trace Example 3 end to end

    Let's trace nums = [4, 6, 2, 5, 4] with circular = 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]
    
  8. 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 n indices. Although there is a while loop inside the for loop, each index is pushed onto decreasing_stack once and popped at most once, making the stack work amortized O(1) per element (averaging out to constant work per step, at most 2n stack operations per pass). Circular mode adds finding max(nums), slicing rotated, and mapping indices back, each taking one O(n) pass.
  • Space — O(n): Storing prev_greater, next_greater, decreasing_stack, and the output list (plus rotated in circular mode) each use at most n integers.

Edge cases

  • Empty array (nums = []): Returns [] in both modes (circular_spans returns early before calling max([])).
  • Single element (nums = [7]): prev_greater = [-1] and next_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 span n ([3, 3, 3]).
  • Equal elements split by a larger peak (nums = [4, 6, 2, 5, 4]): Linearly each outer 4 is isolated (1), whereas circularly both 4s join around the boundary (2) and 5 reaches across both (4).
  • Multiple copies of the global maximum in circular mode ([1, 4, 2, 4, 3]): Rotating to the first 4 gives rotated = [4, 2, 4, 3, 1], where both 4s still have prev_greater = -1 and next_greater = 5, so every copy of the global maximum rightly gets span n = 5.
  • Negative integers ([-2, -5, -1, -3]): Only relative <= comparisons are performed, so negative numbers behave identically to positive ones (-1 is the maximum and spans all 4 items).

Common mistakes

  • Using < instead of <= in the stack while loop: 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] and next_greater[i] are the excluded wall indices themselves, the count of elements strictly between them is next_greater[i] - prev_greater[i] - 1 (not next_greater[i] - prev_greater[i]).
  • Doubling the array nums + nums without capping at n: If you run linear_spans(nums + nums) directly, the global maximum spans all 2n elements of the doubled array instead of n, and smaller elements near the seam can get truncated if read from the wrong copy. Rotating to max(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 supporting O(log n) insertion and predecessor/successor queries) of already-processed indices. When processing value v, the tree contains every index with value > v, so binary-searching i's neighbors immediately gives prev_greater[i] and next_greater[i]. Because Python's standard library lacks a balanced search tree and the monotonic stack runs in O(n) time, the stack is both faster and shorter to write.
  • Two-pass scan over 2n virtual indices for circular mode (O(n) without rotating): You can scan k from 0 to 2n - 1 reading nums[k % n] to find each index's circular distance to the next strictly greater element on the right and on the left, capping at n when no greater element exists. Rotation achieves the same O(n) bound while reusing linear_spans unchanged.

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 while conditions 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] = 5 can wrap left across trailing < 5 elements up to the last 5, so scanning 2n virtual indices (k % n) with < handles both unique and tied global maximums uniformly in O(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 at i must 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 index i.
  • 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 popping i from the active stack reveals next_greater[i] on the fly.

Follow-up questions

Similar questions

More Moloco interview questions

All 5 Moloco questions →