KatInterview

Skyline Visible Buildings Count

Stacks & QueuesAuto-graded · 17 test cases
MediumAuto-gradedStacks & Queuesmonotonic stackarrayssimulation

Last updated

Tests ability to use a monotonic stack to count, for each building, how many previous buildings are visible looking back from it along a city skyline.

Skyline Visible Buildings Count

You are given a list of building heights representing a city skyline viewed from above along a straight avenue. Buildings are indexed left to right.

For each building at index i, a previously seen building at index j < i is visible from building i if and only if there is no building at any index k with j < k < i whose height is strictly greater than or equal to the height of building j.

More precisely, building j is visible from i when every building strictly between j and i has height strictly less than heights[j].

Equivalently, the set of buildings visible looking left from building i is exactly the set of buildings whose heights form a strictly decreasing sequence ending just before position i — i.e., the contents of the monotonic (strictly-decreasing) stack maintained from left to right at the moment just before processing index i.

Your task: return a list result of the same length as heights, where result[i] is the count of buildings visible looking left from building i.

  • result[0] is always 0 (no buildings to the left).
  • The building at index i itself is not counted.

Constraints

  • 1 <= len(heights) <= 2000
  • 1 <= heights[i] <= 10^6
  • All values are positive integers.
  • The input list may contain duplicate heights.
  • The returned list must have the same length as heights.

Examples

Example 1

Input: count_visible_buildings([3, 1, 4, 2, 5])

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

Example 2

Input: count_visible_buildings([5, 4, 3, 2, 1])

Output: [0, 1, 2, 3, 4]

Example 3

Input: count_visible_buildings([1, 1, 1, 1])

Output: [0, 1, 1, 1]

Hints

Hint 1

Think about which previous buildings are blocked: a building j is invisible from i if some building between j and i is at least as tall as building j. What data structure naturally discards such buildings as you scan left to right?

Hint 2

A monotonic strictly-decreasing stack keeps exactly the buildings that have not yet been 'blocked' by a taller-or-equal successor. The size of that stack just before you process index i is your answer for result[i].

Hint 3

When pushing a new building onto the stack, pop all buildings whose height is less than or equal to the current building's height — they can no longer be seen from any future position. The number of remaining elements (before the push) is the count for the current index.