2282. Number of People That Can Be Seen in a Grid

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 2282

class Solution:
    def seePeople(self, heights: List[List[int]]) -> List[List[int]]:
        def f(nums: List[int]) -> List[int]:
            n = len(nums)
            stk = []
            res = [0] * n
            for i in range(n - 1, -1, -1):
                while stk and stk[-1] < nums[i]:
                    res[i] += 1
                    stk.pop()
                if stk:
                    res[i] += 1
                while stk and stk[-1] == nums[i]:
                    stk.pop()
                stk.append(nums[i])
            return res

        res = [f(row) for row in heights]
        m, n = len(heights), len(heights[0])
        for j in range(n):
            add = f([heights[i][j] for i in range(m)])
            for i in range(m):
                res[i][j] += add[i]
        return res