DSA Stacks

Number of Visible People in a Queue

Right-to-left monotonic decreasing stack — each pop counts a visible person.

Hard
Time O(n) Space O(n)
LeetCode
3 min read
monotonic-stack

Problem#

People stand in line with heights given by heights. Person i can see person j > i if min(heights[i..j-1]) < min(heights[i], heights[j]) — informally, no one taller stands between them. Return, for each person, how many people to their right they can see.

Examples#

  • heights = [10,6,8,5,11,9][3,1,2,1,1,0]
  • heights = [5,1,2,3,10][4,1,1,1,0]

Constraints#

  • n == heights.length, 1 <= n <= 10^5, all heights distinct, 1 <= heights[i] <= 10^5.

Approach#

Process right to left with a monotonic decreasing stack. For each person i, count the people they see: every shorter person on the stack is visible (pop and count), then if a taller person remains on the stack, they’re also visible (count one extra).

Solution#

Number of Visible People in a Queue
class Solution {
public:
vector<int> canSeePersonsCount(vector<int>& heights) {
int n = heights.size();
vector<int> ans(n, 0);
stack<int> st;
for (int i = n - 1; i >= 0; --i) {
while (!st.empty() && st.top() < heights[i]) {
st.pop();
ans[i]++;
}
if (!st.empty()) ans[i]++;
st.push(heights[i]);
}
return ans;
}
};

Editorial#

Anyone shorter than i who would otherwise be visible from a later person is blocked once i joins the queue. So i sees the strictly-increasing prefix of the stack (popping each), plus the first taller person if any (the “blocker”). Each person is pushed and popped at most once.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.