425. Count Visible Buildings
Asked in
Count Visible Buildings

Buildings stand in a row from left to right. Every building has a unique height.

From the rooftop of a building, a later building is visible if every building between them is shorter than both buildings.

For each building, count how many later buildings are visible from its rooftop.

Class

BuildingVisibilityAnalyzer

Method

countVisibleBuildings

List<Integer> countVisibleBuildings( List<Integer> buildingHeights )

Parameters

  • buildingHeights: The unique heights of the buildings in their left-to-right order.

Returns

Return a list where the value at index i is the number of later buildings visible from building i.

Visibility Rules

  • Buildings are indexed from 0.
  • Building i can only see a building j when i < j.
  • Every building strictly between i and j must be shorter than both buildingHeights[i] and buildingHeights[j].
  • Two consecutive buildings can always see each other because there is no building between them.
  • The final building has no later buildings to see.

Constraints

  • 1 ≤ buildingHeights.size() ≤ 100,000
  • 1 ≤ buildingHeights[i] ≤ 100,000
  • All values in buildingHeights are unique.

Example 1

countVisibleBuildings( buildingHeights = List.of(12, 5, 10, 3, 8, 14, 7) )

Output: List.of(3, 1, 3, 1, 1, 1, 0)

Building 0, with height 12, can see buildings 1, 2, and 5.

Building 2, with height 10, can see buildings 3, 4, and 5.

Example 2

countVisibleBuildings( buildingHeights = List.of(4, 11, 7, 9, 2) )

Output: List.of(1, 2, 1, 1, 0)

Building 1, with height 11, can see buildings 2 and 3. The building between them has height 7, which is shorter than both 11 and 9.

Example 3

countVisibleBuildings( buildingHeights = List.of(18) )

Output: List.of(0)

There is only one building, so there are no later buildings to see.



Please use Laptop/Desktop or any other large screen to add/edit code.