Widest Span Between Two Dominating Ends
Stacks & QueuesAuto-graded · 22 test casesLast updated
Find the longest subarray whose two end values are each strictly larger than everything between them, using a monotonic stack to avoid checking all pairs.
You are given a list of integers values. Consider a span to be a pair of positions (i, j) with i < j, covering the elements values[i], values[i+1], ..., values[j]. Its length is j - i + 1.
A span is dominated by its ends if every element strictly between the two ends is strictly smaller than both end values. In other words:
max(values[i+1..j-1]) < min(values[i], values[j])
A span with no interior elements (j = i + 1) always qualifies, since there is nothing to compare.
Return the length of the longest span that is dominated by its ends. If values has fewer than two elements, no span exists, so return 0.
Note that equal values are not "strictly smaller". For example, in [2, 2, 2] the span covering all three elements does not qualify, because the interior 2 is not smaller than the ends. In [2, 1, 2], however, the whole list qualifies.
Checking every pair of positions is too slow for the input sizes below. Aim for a solution that is better than quadratic.
Constraints
0 <= len(values) <= 10^5-10^9 <= values[k] <= 10^9- The function returns a single integer: the maximum span length, or
0iflen(values) < 2. - Any list with at least two elements has an answer of at least
2, because adjacent pairs always qualify.
Examples
Example 1
Input: longest_span_with_dominating_ends([1, 3, 2, 4, 1])
Output: 3
Example 2
Input: longest_span_with_dominating_ends([4, 2, 6])
Output: 3
Hints
Hint 1
Consider a qualifying span and look at which of its two ends is smaller (or equal). What must be true of the nearest element on the other side of that end?
Hint 2
For a qualifying span, either the right end is the nearest element at or to the right of the left end with value greater than or equal to it, or the left end is the nearest such element to the left of the right end. That leaves only O(n) candidate pairs.
Hint 3
Compute both candidate families with a monotonic stack, one left-to-right pass for each direction. Be careful with ties: use <= when popping in one pass and < in the other so that equal values are still paired as ends.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key observation. Take any qualifying span (i, j) with more than two elements. Compare its two ends.
- If
values[i] <= values[j], every interior element is strictly smaller thanvalues[i]. So no element betweeniandjis>= values[i], which meansjis exactly the nearest index to the right ofiwhose value is>= values[i]. - If
values[i] >= values[j], the symmetric argument showsiis the nearest index to the left ofjwhose value is>= values[j].
The converse also holds. If j is the nearest index right of i with values[j] >= values[i], everything between them is < values[i] <= values[j], so the span qualifies. The same holds for the leftward version.
So every qualifying span is of the form (i, nextGE(i)) or (prevGE(j), j). That gives at most 2n candidates, and every candidate qualifies. The answer is the longest candidate, with a floor of 2 when n >= 2. (Adjacent pairs are also covered by these candidates.)
Computing the candidates with monotonic stacks.
- Next greater-or-equal pass. Scan left to right, keeping a stack of indices with strictly decreasing values. When
values[i]arrives, pop every indexleftwithvalues[left] <= values[i]. Each popped index hasias its nearest greater-or-equal element to the right, so recordi - left + 1. - Previous greater-or-equal pass. Scan left to right again, popping only indices with values strictly smaller than
values[i]. If the stack is non-empty afterward, its top is the nearest index to the left with value>= values[i], so recordi - top + 1. Equal values are deliberately kept on the stack so they can serve as an end.
The <= versus < difference handles ties: in [2, 1, 2] the two 2s pair up (length 3), while in [2, 2, 2] each 2 pairs only with its immediate neighbor (length 2), since the interior 2 blocks the wider span.
Why it is correct
Every qualifying span is among the candidates (by the key observation), and every candidate qualifies (by the converse). The two stack passes compute exactly these candidates, so taking the maximum gives the right answer. Fewer than two elements yields 0 because no span exists.
Complexity
- Time: O(n). In each pass every index is pushed once and popped at most once.
- Space: O(n) for the stack, for example on a strictly decreasing list.
Reference solution
from typing import List
def longest_span_with_dominating_ends(values: List[int]) -> int:
n = len(values)
if n < 2:
return 0
best = 2
# Pass 1: pair each index with the nearest index to its right whose
# value is greater than or equal to it.
stack = []
for i, v in enumerate(values):
while stack and values[stack[-1]] <= v:
left = stack.pop()
best = max(best, i - left + 1)
stack.append(i)
# Pass 2: pair each index with the nearest index to its left whose
# value is greater than or equal to it.
stack = []
for i, v in enumerate(values):
while stack and values[stack[-1]] < v:
stack.pop()
if stack:
best = max(best, i - stack[-1] + 1)
stack.append(i)
return best