Imagine you're a city planner designing a coastal neighborhood where residents want to enjoy beautiful ocean views! ๐๏ธ๐
You have n buildings arranged in a straight line along the coast. Each building has a specific height given in an array heights, where heights[i] represents the height of the i-th building. The ocean is located to the right of all buildings.
A building has an ocean view if and only if all buildings to its right are shorter than it. In other words, there are no taller buildings blocking its view to the ocean.
Your task: Return a list of indices (0-indexed) of all buildings that have an unobstructed ocean view, sorted in increasing order.
Example: If buildings have heights [4,2,3,1], then buildings at indices 0, 2, 3 have ocean views because:
- Building 0 (height 4): All buildings to its right (2,3,1) are shorter โ
- Building 1 (height 2): Building at index 2 (height 3) is taller โ
- Building 2 (height 3): Building to its right (height 1) is shorter โ
- Building 3 (height 1): No buildings to its right โ
Input & Output
Visualization
Time & Space Complexity
Single pass through the array from right to left, each element processed once
Only using constant extra space for variables (not counting output array)
Constraints
- 1 โค heights.length โค 105
- 1 โค heights[i] โค 109
- The ocean is to the right of the buildings