Problem
There are n buildings in a line. You are given an integer array heights of size n that represents the heights of the buildings in the line.
The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a smaller height.
Return a list of indices (0-indexed) of buildings that have an ocean view, sorted in increasing order.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Constraints:
1 <= heights.length <= 10^51 <= heights[i] <= 10^9
Solution
Method 1 – Stack from Right
Intuition
A building has an ocean view if all buildings to its right are shorter. Traverse from right to left, keeping track of the maximum height seen so far.
Approach
- Start from the rightmost building, which always has an ocean view.
- For each building from right to left, if its height is greater than the max seen so far, add its index to the result.
- Reverse the result to get indices in increasing order.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(n)