You are given an array of integers heights of size n representing a row of buildings, where heights[i] is the height of the ith building.
There is an ocean located to the far right of the buildings. A building has an ocean view if every building to its right is strictly shorter than it.
Return a list of indices (0-indexed) of the buildings that have an ocean view, sorted in increasing order.
Example 1:
Input: heights = [4,2,3,2,1]
Output: [0,2,3,4]Example 2:
Input: heights = [1,3,2,4,2,5,1]
Output: [5,6]Example 3:
Input: heights = [9,8,7,7,6,5,4,3]
Output: [0,1,3,4,5,6,7]Constraints:
1 <= heights.length <= 100,000.1 <= heights[i] <= 1,000,000,000Before attempting this problem, you should be comfortable with:
A building has an ocean view if no building to its right is taller or equal in height. The ocean is to the right of all buildings. The simplest approach is to check each building individually: for every building, scan all buildings to its right and see if any of them block the view.
i, check all buildings from index i+1 to the end.We can use a monotonic decreasing stack to efficiently track buildings with ocean views. As we scan from left to right, whenever we encounter a building that is taller than or equal to the building at the top of the stack, the stack building loses its ocean view (because this new building blocks it). We pop such buildings and push the current one. The remaining buildings in the stack at the end all have ocean views.
The most elegant approach is to scan from right to left. A building has an ocean view if it is strictly taller than every building to its right. We only need to track the maximum height seen so far as we traverse from the rightmost building toward the left.
A building loses its ocean view if any building to its right is taller OR EQUAL in height. Using strictly greater than (>) instead of greater than or equal (>=) incorrectly keeps buildings that are blocked by same-height buildings.
# Wrong: same height doesn't block
if heights[i] > heights[j]: # Misses equal heights
# Correct: equal or greater blocks the view
if heights[i] <= heights[j]:
has_view = FalseWhen iterating from right to left (the optimal approach), indices are collected in reverse order. Forgetting to reverse the final result returns indices in descending order instead of the required ascending order.
An array with one building should return [0] since the only building always has an ocean view. Edge case handling ensures the rightmost building is always included in the initial result.