Problem Description
Given an m x n grid where each cell represents the positive integer height of a person, determine for every person (i, j) the number of people they can see. A person can only see to the right (in the same row) or downward (in the same column) under the condition that every person between them is strictly shorter than both the observer and the target.
Key Insights
- The visibility is only checked in one of two directions: right in the same row and downward in the same column.
- In each direction, a person can see another if every person in between is shorter than both.
- The problem naturally lends itself to using a monotonic stack to efficiently track heights and count visible persons.
- Separate processing for rows and columns followed by summing counts will give the final answer for each cell.
Space and Time Complexity
Time Complexity: O(m * n) — each cell is processed in both row-wise and column-wise passes. Space Complexity: O(max(m, n)) — extra space for the monotonic stack in the worst-case scenario for either a row or a column.
Solution
The solution leverages a monotonic stack approach to count visible persons in each direction independently. For the row-wise pass, for each row we iterate from left to right and maintain a stack that helps us count how many persons can be seen from the current position. If the current height is larger than the ones in the stack, those persons are popped because the current person blocks them. We then add one more if the stack isn’t empty (meaning the next taller/equal person is still visible). The same logic is applied column-wise by iterating through each column from top to bottom. Finally, we sum the counts from both passes to construct the final answer grid.