Number of Visible People in a Queue

HardMonotonic Stack🧩 Monotonic StackLeetCode #1944 ↗Updated

Problem

People stand in a line facing right; heights[i] is the (distinct) height of person i. Person i can see person j > i when everybody standing strictly between them is shorter than both of them. Return an array whose i-th entry is how many people person i can see.
Inputheights = [10,6,8,5,11,9]Output[3,1,2,1,1,0]
Inputheights = [5,1,2,3,10]Output[4,1,1,1,0]

1 ≤ n ≤ 105  ·  1 ≤ heights[i] ≤ 105  ·  all heights distinct

Try it yourself

Java
class Solution {
    public int[] canSeePersonsCount(int[] heights) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Looking right, person i sees a strictly increasing run of people up to the first one taller than them. Processing from the right with a decreasing stack, the people i pops are exactly that run, plus one more if someone taller remains on the stack.
PatternMonotonic Stack

Instinct Each element needs its nearest bigger or smaller neighbour (next warmer day, span, widest bar) - keep a sorted stack of waiting indices.

Memory hack Tall people block the view - a newcomer kicks out everyone shorter waiting behind, and each kicked-out person just found their answer.

Open the Monotonic Stack guide →

Approaches

Brute ForceCheck Every Pair Directly

Time O(n3)Space O(1) extra

For each pair (i, j) compute the tallest person strictly between them and test that both endpoints are taller than it. This is the visibility rule copied literally.

Java
public int[] canSeePersonsCount(int[] heights) {
    int n = heights.length;
    int[] ans = new int[n];
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            int tallestBetween = 0;
            for (int m = i + 1; m < j; m++) {
                tallestBetween = Math.max(tallestBetween, heights[m]);
            }
            if (Math.min(heights[i], heights[j]) > tallestBetween) ans[i]++;
        }
    }
    return ans;
}

Obviously correct, useful as a reference, but cubic.

At a glance

LevelApproachTimeSpace
Brute ForceCheck Every Pair DirectlyO(n3)O(1) extra
BetterRunning Maximum with Early StopO(n2)O(1) extra
OptimalRight-to-Left Decreasing StackO(n)O(n)
Common pitfalls
  • Counting only people taller than i — shorter ones can be visible too.
  • Forgetting the extra +1 for the first taller person left on the stack.
  • Not stopping at the first person at least as tall as i in the O(n2) scan.
Interview tips
  • Draw a small example and notice the visible people form an increasing run.
  • State the stack invariant: strictly decreasing heights from bottom to top.
  • Mention distinct heights; with ties you would have to decide how equals block.
Pattern
Monotonic stack → counting or finding elements “until the next greater one” on one side.
My notes saved in this browser