AlgoInsight

DSA problem

Number of Visible People in a Queue

HardMonotonic StackPattern: Monotonic Stacktop300AmazonGoogleMicrosoftBloomberg

There are n people standing in a queue numbered 0 to n - 1 from left to right. You are given an array heights of distinct positive integers where heights[i] is the height of the i-th person. A person at index i can see another person at index j if i < j and min(heights[i], heights[j]) > max(heights[k]) for every k strictly between i and j.

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

The brute force enumerates each pair and checks the "no taller person in between" condition, taking O(n²) time at worst. For n up to 10⁵ we need linear time.

The key observation is that as we scan right-to-left and maintain a monotonic increasing stack of heights to the right of the current index, person i can see exactly:

So answer[i] is the number of pops plus (1 if stack is non-empty after the pops, else 0). Each index is pushed and popped at most once, giving an O(n) algorithm overall.

Examples

Example 1
Input: heights = [10,6,8,5,11,9]
Output: [3,1,2,1,1,0]
Explanation: Person 0 sees persons 1, 2, and 4 (heights 6, 8, 11) — 6 < 8 < 11. Person 1 sees 2. Person 2 sees 3 and 4. Person 3 sees 4. Person 4 sees 5. Person 5 sees no one.
Example 2
Input: heights = [5,1,2,3,10]
Output: [4,1,1,1,0]
Explanation: Person 0 (5) sees 1, 2, 3 (each shorter) and then 10 (the first taller blocks nothing because it is the next one and visible). Total 4. Each later person sees the next taller one.
Example 3
Input: heights = [3,1,2]
Output: [2,1,0]
Explanation: Person 0 (3) sees 1 (shorter) and 2 (shorter). Person 1 (1) sees 2 (taller, blocks nothing). Person 2 sees no one.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

monotonic-stackstackarray

Browse all DSA problems