Buildings With an Ocean View — LeetCode 1762 Python Solution
MediumLeetCode PremiumStackArrayMonotonic Stack
- Problem
- #1762
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(1) auxiliary |
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
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.