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 Problem Overview4231i=0 ✓i=1 ✗i=2 ✓i=3 ✓🌊 OCEANBuildings with view:Index 0: height 4Index 2: height 3Index 3: height 1Index 1 blocked bybuilding at index 2Input: [4,2,3,1] → Output: [0,2,3]
Understanding the Visualization
1
Input
Array of building heights [4,2,3,1]
2
Process
Check which buildings can see ocean (no taller buildings to the right)
3
Output
Indices of buildings with ocean view [0,2,3]
Key Takeaway
🎯 Key Insight: Process buildings from right to left, tracking the maximum height seen so far to determine ocean view eligibility
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