Number of People That Can Be Seen in a Grid - Problem
You are given an m x n 0-indexed 2D array of positive integers heights where heights[i][j] is the height of the person standing at position (i, j).
A person standing at position (row1, col1) can see a person standing at position (row2, col2) if:
- The person at
(row2, col2)is to the right or below the person at(row1, col1). More formally, this means that eitherrow1 == row2 && col1 < col2orrow1 < row2 && col1 == col2. - Everyone in between them is shorter than both of them.
Return an m x n 2D array of integers answer where answer[i][j] is the number of people that the person at position (i, j) can see.
Input & Output
Example 1 — Basic Grid
$
Input:
heights = [[3,1,4,2,5],[1,2,3,4,5]]
›
Output:
[[2,1,2,1,0],[0,0,0,0,0]]
💡 Note:
Person at (0,0) with height 3 can see (0,1) height 1 and (1,0) height 1. Person at (0,1) with height 1 can see (0,2) height 4. Person at (0,2) with height 4 can see (0,3) height 2 and (1,2) height 3. Person at (0,3) with height 2 can see (0,4) height 5. Last column and bottom row see 0 people.
Example 2 — Single Row
$
Input:
heights = [[1,2,3]]
›
Output:
[[2,1,0]]
💡 Note:
Person at (0,0) height 1 can see both (0,1) height 2 and (0,2) height 3. Person at (0,1) height 2 can see (0,2) height 3. Person at (0,2) sees no one.
Example 3 — Blocking Heights
$
Input:
heights = [[5,1,2,3,4],[1,1,1,1,1]]
›
Output:
[[4,3,2,1,0],[0,0,0,0,0]]
💡 Note:
Person at (0,0) height 5 can see everyone to the right since they're all shorter. Bottom row can't see anyone since they're at the last row and no one is to their right in same row.
Constraints
- 1 ≤ m, n ≤ 50
- 1 ≤ heights[i][j] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
2D array of heights representing people
2
Visibility Rules
Can only see right in same row or down in same column
3
Count Visible
Count people visible from each position
Key Takeaway
🎯 Key Insight: Use monotonic decreasing stack to efficiently track which people remain visible after processing each position
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code