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 either row1 == row2 && col1 < col2 or row1 < 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
Number of People That Can Be Seen in a Grid314123Input: heights = [[3,1,4],[1,2,3]]Person at (0,0) can see right → and down ↓Visibility from (0,0)• Right: height 1 < 3 ✓• Down: height 1 < 3 ✓• Total visible: 2211Output: [[2,1,1],[0,0,0]]
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
Asked in
Amazon 15 Google 12 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
467 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen