Number of Visible People in a Queue LeetCode solution in Python

1
# Runtime: 2162 ms (Top 20.79%) | Memory: 30.1 MB (Top 6.96%)
2

3

4
class Solution:
5
def canSeePersonsCount(self, heights: List[int]) -> List[int]:
6
ans = []
7
stack = []
8
n = len(heights)
9
for i in range(n - 1, -1, -1):
10
if len(stack) == 0:
11
ans.append(0)
12
stack.append(heights[i])
13
else:
14
if heights[i] < stack[-1]:
15
ans.append(1)
16
stack.append(heights[i])
17
else:
18
ctr = 0
19
while len(stack) > 0 and stack[-1] < heights[i]:
20
ctr += 1
21
stack.pop()
22
if len(stack) == 0:
23
ans.append(ctr)
24
else:
25
ans.append(ctr + 1)
26
stack.append(heights[i])
27
return ans[::-1]

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0