Number of Visible People in a Queue

Hard

Topics
ArrayStackMonotonic Stack

nums holds the heights of people standing in a queue, all facing to the right. Heights are distinct.

Person i can see person j (with j > i) if j is taller than everybody strictly between them — that is, min(nums[i], nums[j]) > max(nums[i+1..j-1]).

Return an array where entry i is the number of people person i can see.

Example 1

heights10685119
answer301122131405
person 0 and everyone they can see
Everyone looks to their right only. Person i can see person j when nobody standing between them is as tall as the shorter of the two, so a tall person blocks everything behind them. The shaded bars are person 0 together with the 3 people they see, and the 2 unshaded bars further right are hidden behind one of them. The answer row gives that count for every position, and the last person always sees nobody.
Equal heights block each other, so a person is not seen past someone their own height.
Input:  nums = [10,6,8,5,11,9]
Output: [3,1,2,1,1,0]
Explanation: Person 0 sees 6, then 8 over the top of 6, then 11 over the top of 8 — but not 5, which 8 hides, nor 9, which 11 hides.

Example 2

heights512310
answer4011121304
person 0 and everyone they can see
The shaded bars are person 0 together with the 4 people they see.
Input:  nums = [5,1,2,3,10]
Output: [4,1,1,1,0]
Explanation: Each of the rising heights is visible to person 0 in turn; the last person sees nobody.

Example 3

heights1
answer00
the only person
Everyone looks to their right only, so the person at the back of the queue can never see anyone. With a single person that is the whole answer, and their height does not enter into it.
Input:  nums = [1]
Output: [0]
Explanation: Nobody to the right.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5
  • All heights are distinct
Editorial — intuition, approach, complexity and pitfalls

Intuition

Checking every pair and scanning between them is cubic, and the rule itself suggests something much simpler. Walking rightwards from person i, you see somebody exactly when they are taller than everybody seen so far — so what person i sees is the sequence of running maxima to their right, and the view stops at the first person taller than i.

Turn that around and process from the right end. Hold the people who are still visible to whoever comes next, shortest at the top. When a new person arrives, everybody shorter than them is visible to them — and then hidden from everyone further left, because the newcomer blocks them.

So each arrival pops the shorter people off, counting them, and then is pushed. One extra sighting is added if anybody remains after the popping: that is the first person taller than the newcomer, who is visible and ends the view.

Every person is pushed once and popped once, which is what turns a cubic rule into a single pass.

Approach

  1. Keep a stack of heights that is increasing from the top downwards, and an output array.
  2. Walk the indices from right to left. For the current person, pop every stack entry shorter than them, counting one sighting each.
  3. If the stack is still non-empty, add one more sighting — that entry is taller and is the last person visible.
  4. Push the current height and move left.

Walkthrough

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

right to left; stack holds heights still visible leftwards

i  height  pops (shorter)   extra?        count  stack after
5    9      --               no            0      [9]
4   11      9                no            1      [11]
3    5      --               yes (11)      1      [11, 5]
2    8      5                yes (11)      2      [11, 8]
1    6      --               yes (8)       1      [11, 8, 6]
0   10      6, 8             yes (11)      3      [11, 10]

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

Person 0 popped 6 and 8 -- both visible -- and then stopped at
11, which is counted and blocks everything beyond it.

Complexity

  • Time — O(n): each height is pushed once and popped once.
  • Space — O(n): the stack, which in the worst case holds everybody.

Common Pitfalls

  • Forgetting the extra sighting for the first taller person. They are visible — example 1 counts 11 for person 0 — and only everything beyond them is hidden.
  • Counting that taller person and then popping them. They stay on the stack, because they are visible to people further left too.
  • Walking left to right. The stack only works from the right, since visibility looks rightwards.
  • Reading the rule as "taller than me". It is "taller than everybody between us", which is why person 0 in example 1 sees 6 even though 6 is shorter.

Full Solution — all languages

class Solution:
    def canSeePersonsCount(self, nums):
        n = len(nums)
        out = [0] * n
        stack = []
        for i in range(n - 1, -1, -1):
            seen = 0
            while stack and stack[-1] < nums[i]:
                stack.pop()
                seen += 1
            if stack:
                seen += 1
            out[i] = seen
            stack.append(nums[i])
        return out
SensAI
Beta
Tap the mic to stop voice mode