Maximum Width Ramp (LeetCode 962): Solution and Explanation

Medium
Array
Stack
Monotonic Stack
Two Pointers

Given an integer array, find the widest pair of indices i < j with nums[i] <= nums[j], and return j - i (or 0 if no such pair exists).

Intuition

Look at the possible left ends. If some earlier index already holds a value less than or equal to nums[i], that earlier index pairs with every j that i can pair with, and it is farther left. So i can never be the left end of the best ramp.

That leaves only the prefix minimums: indices whose value is smaller than everything before them. Read left to right, their values strictly fall, which is exactly a decreasing stack.

Now try right ends from the far right. For the stack top (the smallest candidate value), the first j from the right with nums[j] >= nums[top] is its best partner, because any j further left is narrower. So pop it, record the width, and check the next candidate against the same j.

Approach: Monotonic stack of left ends

  1. Scan i from 0 to n - 1. Push i when the stack is empty or nums[i] is smaller than the value at the stack top.
  2. Set best = 0.
  3. Scan j from n - 1 down to 0. While the stack is not empty and the value at its top is <= nums[j], pop the top and set best = max(best, j - top).
  4. Return best.

Step-by-step example

nums = [6,0,8,2,1,5]
  1. Pass 1: index 0 (6) is pushed, index 1 (0) is smaller so it is pushed. Values 8, 2, 1, 5 are not below 0, so they are skipped. The stack is [0, 1].
  2. Pass 2, j = 5 (value 5): the top is index 1 with value 0 <= 5, so pop it. Width 5 - 1 = 4, best = 4.
  3. The next top is index 0 with value 6 > 5, so stop popping and move left.
  4. j = 4 (1) and j = 3 (2) are both below 6. At j = 2 (value 8), index 0 pops with width 2, which does not beat 4.
  5. The stack is empty, so the answer is 4.

Code: Python, Java, C++

1class Solution:
2    def maxWidthRamp(self, nums: List[int]) -> int:
3        stack = []
4        for i, x in enumerate(nums):
5            if not stack or nums[stack[-1]] > x:
6                stack.append(i)
7        best = 0
8        for j in range(len(nums) - 1, -1, -1):
9            while stack and nums[stack[-1]] <= nums[j]:
10                best = max(best, j - stack.pop())
11        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index is pushed at most once in the first pass and popped at most once in the second, and the j loop runs n times.

Space

O(n)

The stack can hold every index when the array is strictly decreasing.

Other approaches

Check every pair (time O(n^2), space O(1))

Two nested loops try every (i, j) and keep the widest valid one. Simple, but far too slow for 50,000 elements.

Sort indices by value (time O(n log n), space O(n))

Sort the indices by (value, index). Walk them in order while tracking the smallest index seen so far; each index j can form a ramp with that smallest earlier-in-order index.

Suffix maximum with two pointers (time O(n), space O(n))

Build an array of suffix maximums, then move i and j forward together: advance j while suffixMax[j] >= nums[i], otherwise advance i. It is also linear.

Common mistakes

  • Pushing on <= instead of < in the first pass. An equal value later in the array is never a better left end, and duplicates only waste stack space.
  • Popping on < instead of <= in the second pass. A ramp allows equal values, so [7, 7] has width 1.
  • Sweeping j from left to right. The right-to-left order is what makes it safe to pop a candidate as soon as it fits.
  • Stopping after the first pop for a given j. Several candidates can fit the same right end, and each must be popped and measured.

Frequently asked questions

Why can a popped candidate never do better later?

j only moves left from there, so any later partner would give a smaller width than the one just recorded.

Why does the stack hold falling values?

An index is pushed only when its value is below the current top. A value that is not smaller would always lose to the earlier, smaller index as a left end.

What if no ramp exists?

That happens only when the array strictly decreases. Each index then pops itself with width 0, and the answer stays 0.

What are the time and space costs?

O(n) time, since each index is pushed and popped at most once, and O(n) space for the stack.