Skip to content

Commit c5ff8a4

Browse files
committed
Sync LeetCode submission Runtime - 18 ms (67.27%), Memory - 31.1 MB (22.17%)
1 parent d50040e commit c5ff8a4

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<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>
2+
3+
<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>
4+
5+
<p>Return a list of indices <strong>(0-indexed)</strong> of buildings that have an ocean view, sorted in increasing order.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> heights = [4,2,3,1]
12+
<strong>Output:</strong> [0,2,3]
13+
<strong>Explanation:</strong> Building 1 (0-indexed) does not have an ocean view because building 2 is taller.
14+
</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> heights = [4,3,2,1]
20+
<strong>Output:</strong> [0,1,2,3]
21+
<strong>Explanation:</strong> All the buildings have an ocean view.
22+
</pre>
23+
24+
<p><strong class="example">Example 3:</strong></p>
25+
26+
<pre>
27+
<strong>Input:</strong> heights = [1,3,2,4]
28+
<strong>Output:</strong> [3]
29+
<strong>Explanation:</strong> Only building 3 has an ocean view.
30+
</pre>
31+
32+
<p>&nbsp;</p>
33+
<p><strong>Constraints:</strong></p>
34+
35+
<ul>
36+
<li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li>
37+
<li><code>1 &lt;= heights[i] &lt;= 10<sup>9</sup></code></li>
38+
</ul>
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Approach 3: Monotonic Stack Space Optimization
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def findBuildings(self, heights: List[int]) -> List[int]:
8+
n = len(heights)
9+
answer = []
10+
max_height = -1
11+
12+
for current in reversed(range(n)):
13+
if heights[current] > max_height:
14+
answer.append(current)
15+
max_height = heights[current]
16+
17+
answer.reverse()
18+
return answer
19+

0 commit comments

Comments
 (0)