1944. Number of Visible People in a Queue

Question

CleanShot 2024-09-26 at 14.01.28.png

Code

class Solution:
    def canSeePersonsCount(self, heights: List[int]) -> List[int]:
        
        stack = []
        H = len(heights)
        res = [0] * H


        for i in range(H - 1, -1, -1):
            count = 0


            while stack and heights[stack[-1]] < heights[i]:
                count += 1
                stack.pop()

			# If stack, this is the tallest person from current person's viewpoint
            if stack:
                count += 1

            res[i] = count
            stack.append(i)

        return res