Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1762: Buildings With an Ocean View

In this guide, we solve Leetcode #1762 Buildings With an Ocean View in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Stack, Array, Monotonic Stack

Intuition

We need the next greater or smaller element efficiently, which is exactly what a monotonic stack offers.

Each element is pushed and popped at most once, yielding a linear-time scan.

Approach

Maintain a stack that is either increasing or decreasing, depending on the query.

When the invariant is broken, pop and resolve answers for those indices.

Steps:

  • Scan elements once.
  • Pop while the monotonic condition is violated.
  • Use stack indices to update answers.

Example

Input: heights = [4,2,3,1] Output: [0,2,3] Explanation: Building 1 (0-indexed) does not have an ocean view because building 2 is taller.

Python Solution

class Solution: def findBuildings(self, heights: List[int]) -> List[int]: ans = [] mx = 0 for i in range(len(heights) - 1, -1, -1): if heights[i] > mx: ans.append(i) mx = heights[i] return ans[::-1]

Complexity

The time complexity is O(n)O(n)O(n), where nnn is the length of the array. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy