Drill

ProblemsTypeScript › patterns

The next one taller than this

hardpatternsStacksArraysTypeScript

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.

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

Solve it in the editor →

Where you start

function nextTaller(heights: number[]): number[] {
  
}

Worked examples

CallResult
nextTaller([2,1,2,4,3])[4,2,4,-1,-1]
nextTaller([5,4,3])[-1,-1,-1]
nextTaller([1,2,3])[2,3,-1]
nextTaller([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 TypeScript
function nextTaller(heights: number[]): number[] {
  const answer: number[] = new Array(heights.length).fill(-1);
  const waiting: number[] = [];
  for (let i = 0; i < heights.length; i += 1) {
    while (waiting.length > 0 && heights[waiting[waiting.length - 1]] < heights[i]) {
      answer[waiting.pop() as number] = heights[i];
    }
    waiting.push(i);
  }
  return answer;
}

The same problem in another language

More patterns problems in TypeScript