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