Number of Visible People in a Queue - Problem

There are n people standing in a queue, numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person.

A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]).

Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.

Input & Output

Example 1 — Basic Queue
$ Input: heights = [10,6,8,5,11,9]
Output: [3,1,2,1,1,0]
💡 Note: Person 0 (height 10) can see persons 1, 2, and 4. Person 1 (height 6) can see person 2. Person 2 (height 8) can see persons 3 and 4. Person 3 (height 5) can see person 4. Person 4 (height 11) can see person 5. Person 5 sees no one.
Example 2 — Increasing Heights
$ Input: heights = [5,1,2,3,10]
Output: [4,1,1,1,0]
💡 Note: Person 0 can see everyone to the right since they're all shorter until person 4. Each person can see the next taller person.
Example 3 — Decreasing Heights
$ Input: heights = [10,8,6,4,2]
Output: [4,3,2,1,0]
💡 Note: In decreasing order, each person can see all people to their right since no one blocks the view.

Constraints

  • 1 ≤ heights.length ≤ 105
  • 1 ≤ heights[i] ≤ 109
  • All values in heights are distinct

Visualization

Tap to expand
Number of Visible People in a Queue INPUT 10 i=0 6 i=1 8 i=2 5 i=3 11 i=4 9 i=5 [10, 6, 8, 5, 11, 9] Person can see another if all people between are shorter ALGORITHM STEPS 1 Use Monotonic Stack Traverse array from right to left 2 Pop Shorter People Count visible while popping 3 Check Stack Top If taller exists, add 1 more 4 Push Current Add current height to stack Stack Example (i=0): Stack: [11] Count: 3 Pop 6,8,5 (shorter) See 11 (first taller) Total: 3+1 visible = 3 FINAL RESULT 10 -3- 6 -1- 8 -2- 5 -1- 11 -1- 9 -0- Person 0 (h=10) sees: 6,8,11 Person 1 (h=6) sees: 8 Person 2 (h=8) sees: 5,11 Person 3 (h=5) sees: 11 Person 4 (h=11) sees: 9 Person 5 (h=9) sees: none Output: [3, 1, 2, 1, 1, 0] OK - Verified Time: O(n), Space: O(n) Key Insight: Monotonic decreasing stack efficiently tracks "blocking" people. When we pop shorter people from stack, we can see them. The first taller person remaining blocks our view further. Processing right-to-left lets us know who blocks visibility before processing each person. TutorialsPoint - Number of Visible People in a Queue | Monotonic Stack Approach
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
28.5K Views
Medium Frequency
~25 min Avg. Time
890 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