MediumNo. 1762LeetCode Premium

Buildings With an Ocean View — LeetCode 1762 Python Solution

Pattern
Stack
Topics
Stack, Array, Monotonic Stack
Reading time
2 min

The 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.

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

PythonSolution
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

Time
O(n)where n is the length of the array
Space · auxiliary
O(1)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1762. Buildings With an Ocean View is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0084Largest Rectangle in HistogramHard
0456132 PatternMedium
0503Next Greater Element IIMedium
0654Maximum Binary TreeMedium
0739Daily TemperaturesMedium
0853Car FleetMedium

Frequently asked questions

How hard is LeetCode 1762. Buildings With an Ocean View?

LeetCode 1762. Buildings With an Ocean View is rated Medium on LeetCode.

What is the time complexity of LeetCode 1762. Buildings With an Ocean View?

The Python solution on this page runs in O(n), where n is the length of the array.

What is the space complexity of LeetCode 1762. Buildings With an Ocean View?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 1762. Buildings With an Ocean View cover?

LeetCode 1762. Buildings With an Ocean View is tagged Stack, Array and Monotonic Stack on LeetCode.

Is LeetCode 1762. Buildings With an Ocean View a premium problem?

Yes. LeetCode 1762. Buildings With an Ocean View is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.