Number of Visible People in a Queue

You are given an array heights representing people standing in a queue from left to right. For each person, return how many people to their right they can see. A person can see another person if everyone between them is shorter than both of them. Example: Input: heights = [10,6,8,5,11,9] Output: [3,1,2,1,2,1] Explanation: Person 10 can see 6, 8, and 11; person 6 can only see 8. Pattern focus: Monotonic Decreasing Stack for Next Greater / Visibility.

Input Format

heights = queue heights

Output Format

answer[i] = number of visible people to the right of i

Constraints

  • 1 <= heights.length <= 10^5
  • 1 <= heights[i] <= 10^9

Examples

Example 1:

Input:

heights = [10,6,8,5,11,9]

Output:

[3,1,2,1,1,0]

Explanation:

Person 10 can see 6, 8, and 11; person 11 can see only 9 because it is the first person to the right that is shorter than 11.

Example 2:

Input:

heights = [5,1,2,3,10]

Output:

[4,1,1,1,0]

Explanation:

The last tallest person is visible to everyone before them.

Loading...
Number of Visible People in a Queue