The Number of Visible People in a Queue problem places people in a queue with different heights. For each person, count how many people to their right they can see. A person at position i can see person j (j > i) if all people between them are shorter than both person[i] and person[j]. This hard coding problem uses a monotonic stack to compute visibility counts efficiently.
Microsoft, Meta, Amazon, Google, Bloomberg, and many others ask this hard stack problem because it tests the monotonic stack for visibility counting. The standard approach — for each i, scan right — is O(n²). The stack-based O(n) solution is the expected answer at top-tier companies. The array, monotonic stack, and stack interview pattern is the core.
Monotonic decreasing stack (process right to left). Process from right to left. For each person i, pop all shorter people from the stack (each popped person is visible to i, plus 1 for the first taller person that stops the pops). The count for person i = number of pops + (1 if stack is non-empty after pops). Push person i onto the stack.
heights = [10,6,8,5,11,9]. Process right to left:
Visibility counting in queues/buildings is a classic monotonic stack application. The key insight: person i sees person j if no person between them is taller than min(h[i], h[j]). The monotonic stack elegantly captures this: each popped element (shorter than current) is visible from current, and the non-popped top (taller) is the final visible person. Practice "buildings with ocean view," "trapping rain water," and "skyline problem" — they all use monotonic stacks for visibility and height analysis.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Largest Rectangle in Histogram | Hard | Solve | |
| Number of Valid Subarrays | Hard | Solve | |
| Buildings With an Ocean View | Medium | Solve | |
| Sum of Subarray Ranges | Medium | Solve | |
| Next Greater Element II | Medium | Solve |