KatInterview

Find the Nearest Taller Building to the Left

Stacks & QueuesAuto-graded · 17 test cases
EasyAuto-gradedStacks & Queuesmonotonic stackarraysstack

Last updated

Tests the ability to use a monotonic stack to efficiently find, for each building in a skyline, the index of the nearest building to its left that is strictly taller.

Nearest Taller Building to the Left

You are given a list of building heights along a street. For each building, you want to find the nearest building to its left that is strictly taller than it.

Given a list heights of n non-negative integers, return a list result of length n where:

  • result[i] is the index of the nearest building to the left of building i that has a strictly greater height than heights[i].
  • If no such building exists (either i == 0 or all buildings to the left are not strictly taller), set result[i] = -1.

Constraints

  • 1 <= n <= 2000
  • 0 <= heights[i] <= 10^6
  • The returned list must have exactly n elements.
  • Indices are 0-based.
  • Equal heights do not qualify — the neighbour must be strictly taller.

Examples

Example 1

Input: nearest_taller_left([3, 1, 4, 1, 5, 9, 2, 6])

Output: [-1, 0, -1, 2, -1, -1, 5, 5]

Example 2

Input: nearest_taller_left([5, 5, 5, 5])

Output: [-1, -1, -1, -1]

Example 3

Input: nearest_taller_left([7])

Output: [-1]

Hints

Hint 1

Think about what information you need to keep around as you scan left to right — do you need every previous building, or can you discard some?

Hint 2

If building A is to the left of building B, and A is not taller than B, can A ever be the answer for any building to the right of B?

Hint 3

Maintain a stack of indices whose heights are in strictly decreasing order from bottom to top; pop elements that are not taller than the current building before checking the top.