Problem 962

Abstract / Summary

Find the largest distance between two indices where the earlier value is less than or equal to the later value.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0962.py

class Solution:
    def maxWidthRamp(self, nums: List[int]) -> int:
        result = 0

        # sorted in reverse
        low = [ ( nums[0], 0 ) ]
        for i in range(1, len(nums)):
            n = nums[i]
            if n < low[-1][0]:
                # lower than anything seen before
                low.append( ( n, i ) )
            else:
                # measure longest ramp
                left  = 0
                right = len(low) - 1
                # binary search for largest number not exceeding n
                while left != right:
                    mid = (left + right) // 2
                    value, pos = low[mid]
                    if value > n:
                        left  = mid + 1
                    else:
                        right = mid

                length = i - low[left][1]
                result = max(result, length)

        return result
28 lines | 918 bytes | submitted December 19, 2023 | GitHub   19% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 56% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Monotonic Stack
  • Stack
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution.maxWidthRamp method computes the maximum width of a ramp in an integer array nums. A ramp is defined by a pair of indices (i, j) such that i < j and nums[i] <= nums[j]; the width is j - i. The algorithm builds a decreasing list of candidate left-hand positions while scanning the array from left to right. For each element it performs a binary search on that list to locate the earliest candidate that satisfies the ramp condition, updates the best width found, and continues.

Construction of the candidate list

The algorithm maintains a list named low that stores pairs (value, index). The list is kept in strictly decreasing order of value. Only indices that introduce a new minimum value are retained, because any later index with a larger value cannot serve as a better left boundary for a ramp.

low = [(nums[0], 0)]
for i in range(1, len(nums)):
    n = nums[i]
    if n < low[-1][0]:
        low.append((n, i))

When n is smaller than the last stored value, the pair (n, i) is appended. This ensures that low always represents the earliest positions of decreasing values seen so far.

Binary search for the matching left index

If the current element n is not smaller than the last entry in low, the algorithm attempts to extend a ramp. It searches low for the leftmost entry whose value does not exceed n. The search uses a classic binary-search loop that converges when left equals right.

left = 0
right = len(low) - 1
while left != right:
    mid = (left + right) // 2
    value, pos = low[mid]
    if value > n:
        left = mid + 1
    else:
        right = mid

When the loop finishes, low[left] holds the earliest index pos such that nums[pos] <= n. The width of the ramp ending at i is then i - pos.

Updating the result

After locating the appropriate left index, the algorithm computes the candidate width and updates the global maximum.

length = i - low[left][1]
result = max(result, length)

The variable result is initialized to zero, which correctly represents the width when no valid ramp exists (for example, a strictly decreasing array).

Edge-case handling

The code gracefully handles several edge conditions without explicit checks.

When nums contains a single element, the initial low list holds that element, the loop body never executes, and the method returns 0, which is the correct maximum ramp width.

If the array is strictly decreasing, every new element is smaller than the previous minimum, so each iteration appends a new entry to low. The binary-search branch is never taken, and result remains 0.

When the array is strictly increasing, low retains only the first element. Each subsequent element triggers the binary-search path, which immediately finds the first entry as the matching left index, yielding widths that grow with the index. The final result becomes len(nums) - 1, the maximal possible ramp width.

Equal values are treated as satisfying the ramp condition because the binary search uses value > n to decide the direction. When value == n, the algorithm moves right to mid, eventually selecting the earliest occurrence of that value, thereby maximizing the width.

Performance optimizations

The algorithm reduces the search space by storing only decreasing minima in low. This pruning limits the size of the binary-search array to the number of distinct decreasing values, which is often far smaller than len(nums).

Binary search on the compact low list provides logarithmic lookup for each element, avoiding a linear scan of all previous indices.

The use of tuple unpacking (value, pos) = low[mid] inside the loop avoids repeated indexing operations, contributing to tighter inner-loop execution.

By updating result only when a larger width is found, the method avoids unnecessary assignments.

Overall, the combination of a decreasing candidate list and binary search yields an efficient solution that scales well with input size.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long row of building blocks standing in a line, where each block has a different height. You want to pick two blocks to make a ramp. The rule is that the block on the left must be shorter than or the same height as the block on the right. You want the two chosen blocks to be as far apart as possible to make the longest ramp you can.

The code starts by walking along the row of blocks. It looks for special blocks that are the shortest ones seen so far and keeps them in a list. When it finds a new block, it checks if this block is taller than or equal to the very first tiny block on the list. If the new block is taller, a helper trick called binary search is used to quickly jump through the list to find the best match. It compares the current block's position with the position of a saved short block to calculate the distance between them. Every time a new distance is calculated, it remembers the biggest one found during the entire walk through the row.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.48 | σ = 0.79

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java JS Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
lzl124631x C++
qiyuangong Java
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lzl124631x C++
qiyuangong Java
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
withaarzoo C++
31 links | 17 authors | 7 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   December 19, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality