Skip to main content
LeetCode 1762, Medium. Topics: Array, Stack, Monotonic Stack. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:

Problem

<p>There are <code>n</code> buildings in a line. You are given an integer array <code>heights</code> of size <code>n</code> that represents the heights of the buildings in the line.</p> <p>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 <strong>smaller</strong> height.</p> <p>Return a list of indices <strong>(0-indexed)</strong> of buildings that have an ocean view, sorted in increasing order.</p>

Examples

Explanation: Building 1 (0-indexed) does not have an ocean view because building 2 is taller.
Explanation: All the buildings have an ocean view.
Explanation: Only building 3 has an ocean view.

Constraints

  • 1 <= heights.length <= 10^5
  • 1 <= heights[i] <= 10^9

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026