#1944

Number of Visible People in a Queue

Hard
ArrayStackMonotonic StackMonotonic StackArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a monotonic stack allows us to efficiently track the heights of people we can see, reducing the need for nested loops.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an answer array of the same length as heights and an empty stack.
  2. 2Step 2: Iterate through the heights from right to left.
  3. 3Step 3: For each height, pop from the stack until the top of the stack is shorter than the current height, counting how many people can be seen.
  4. 4Step 4: Push the current height onto the stack.
solution.py10 lines
1def canSeePeople(heights):
2    n = len(heights)
3    answer = [0] * n
4    stack = []
5    for i in range(n - 1, -1, -1):
6        while stack and heights[stack[-1]] < heights[i]:
7            answer[i] += 1
8            stack.pop()
9        stack.append(i)
10    return answer

Complexity note: The time complexity is linear because each person is pushed and popped from the stack at most once.

  • 1Using a stack helps manage visibility efficiently.
  • 2The problem can be visualized as a series of barriers where only taller people can see over shorter ones.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.