KatInterview

Widest Span Between Two Dominating Ends

Stacks & QueuesAuto-graded · 22 test cases
MediumAuto-gradedStacks & Queuesmonotonic-stackarraysnearest-greater

Last 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 0 if len(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.