Buildings With an Ocean View - 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.

Input & Output

Example 1 — Basic Case
$ Input: heights = [4,2,3,1]
Output: [0,2,3]
💡 Note: Building 0 (height 4) can see ocean because all buildings to its right (2,3,1) are shorter. Building 2 (height 3) can see ocean because building 3 (height 1) is shorter. Building 3 (height 1) is rightmost so it always has ocean view.
Example 2 — All Buildings Have Ocean View
$ Input: heights = [4,3,2,1]
Output: [0,1,2,3]
💡 Note: Heights are in decreasing order, so each building can see over all buildings to its right. All buildings have ocean view.
Example 3 — Only Rightmost Has View
$ Input: heights = [1,3,2,4]
Output: [3]
💡 Note: Building 3 (height 4) is the tallest and rightmost, so only it has ocean view. All other buildings are blocked by building 3.

Constraints

  • 1 ≤ heights.length ≤ 105
  • 1 ≤ heights[i] ≤ 109

Visualization

Tap to expand
Buildings With an Ocean View INPUT 4 idx 0 2 idx 1 3 idx 2 1 idx 3 Ocean heights = [4,2,3,1] n = 4 buildings Green dashed lines show unobstructed ocean views Building at idx 1 (h=2) is blocked by idx 2 (h=3) ALGORITHM STEPS 1 Initialize maxHeight = 0, result = [] Start from right (idx=3) 2 Right to Left Scan For each building from n-1 down to 0 3 Check View If height[i] > maxHeight: Add i to result 4 Update Max maxHeight = max(maxHeight, heights[i]) Trace (right to left): i=3: h=1 > 0 [OK] max=1 i=2: h=3 > 1 [OK] max=3 i=1: h=2 > 3 NO i=0: h=4 > 3 [OK] max=4 Result: [3,2,0] --> reverse FINAL RESULT 4 idx 0 2 idx 1 3 idx 2 1 idx 3 Has ocean view Blocked Output: [0, 2, 3] 3 buildings can see ocean Indices sorted in increasing order Key Insight: Scanning from RIGHT to LEFT allows us to track the maximum height seen so far in O(1) space. A building has an ocean view if its height exceeds the maximum of all buildings to its right. Time: O(n) single pass | Space: O(1) excluding output | The rightmost building always has a view! TutorialsPoint - Buildings With an Ocean View | Single Pass - Track Maximum Height
Asked in
Facebook 15 Google 8 Amazon 5
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen