Drill

ProblemsPython › patterns

The next one taller than this

hardpatternsStacksArraysPython

A shelf-planning tool walks a row of stacked crates and, for each one, reports the height of the first crate to its right that stands taller.

next_taller(heights: list<int>) → list<int>

Solve it in the editor →

Where you start

def next_taller(heights: list[int]) -> list[int]:
    

Worked examples

CallResult
next_taller([2, 1, 2, 4, 3])[4, 2, 4, -1, -1]
next_taller([5, 4, 3])[-1, -1, -1]
next_taller([1, 2, 3])[2, 3, -1]
next_taller([2, 2, 2])[-1, -1, -1]

Hint

Walk once, keeping a stack of the crates still waiting for an answer. Each new height settles every waiting crate shorter than it.

Reference solution in Python
def next_taller(heights: list[int]) -> list[int]:
    answer = [-1] * len(heights)
    waiting = []
    for i, height in enumerate(heights):
        while waiting and heights[waiting[-1]] < height:
            answer[waiting.pop()] = height
        waiting.append(i)
    return answer

The same problem in another language

More patterns problems in Python