Line of Sight Counts for Each Person in a Row
Stacks & QueuesModel answerLast updated
For each person in a row, count how many people further right they can see when anyone standing between must be shorter than both of them. Needs an O(n) approach.
Line of sight in a queue
A row of n people faces forward. You are given an integer array heights, where heights[i] is the height of the person at position i (left to right).
Person i can see person j to their right (j > i) exactly when every person standing strictly between them is shorter than both of them:
heights[k] < min(heights[i], heights[j]) for all i < k < j.
Adjacent people (j = i + 1) always see each other, since nobody is between them.
For each position i, compute how many people to the right of i are visible to person i.
Input
heights: an array ofnintegers.
Output
- An array
ansof lengthn, whereans[i]is the number of people to the right ofithat personican see.
Example
heights = [10, 6, 8, 5, 11, 9]
ans = [3, 1, 2, 1, 1, 0]
Person 0 (height 10) sees the 6, the 8 and the 11. The 5 is hidden behind the 8, and the 9 is hidden behind the 11.
Another case worth checking is [5, 5, 7], which gives [1, 1, 0]. The first person cannot see the 7, because the middle 5 is not strictly shorter than min(5, 7).
Constraints
1 <= n <= 1000001 <= heights[i] <= 10^9- Heights may repeat.
What to provide
Describe your approach, explain why it is correct, give its time and space complexity, and write the code. A solution that checks every pair is too slow at this input size, so aim for something near linear.
Hints
Hint 1
Consider scanning from right to left. Which of the people you have already passed could still matter to someone further left?
Hint 2
Keep a stack of heights that is strictly decreasing from bottom to top. When a new person arrives, everyone on the stack who is shorter than them is visible to them, and also hidden from everyone further left.
Hint 3
After removing the shorter people, if the stack is not empty, the top is at least as tall as the current person and is visible. If it is exactly equal in height, it is also hidden from everyone further left and should be removed. Stop there, and do not count anything deeper.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Process the row from right to left while maintaining a monotonic stack of heights. The stack holds the people to the right who could still be seen by someone further left. From bottom to top the heights are strictly decreasing, so the top is the nearest candidate.
For the current person with height h:
- Pop and count every stack entry shorter than
h. Each is visible to this person. - If the stack is still non-empty, the top is at least as tall as
h. Count it, because it is the first person who blocks the view and is itself visible. If the top equalsh, also pop it. - Store the count as
ans[i]and pushh.
Nothing beyond that first person at least as tall as h can be seen, so the count ends there.
Why it works
Invariant. Before handling position i, the stack contains exactly those j > i with nobody in (i, j) whose height is at least heights[j]. These are the only people anyone at position i or further left could ever see, because anyone else is already hidden behind someone at least as tall as themselves.
Shorter entries are visible. Take a stack entry j with heights[j] < h. Everyone between i and j is shorter than heights[j] (by the invariant), so they are also shorter than min(h, heights[j]). So i sees j.
The first entry at least as tall is visible. Let j be that entry. Everyone between is shorter than heights[j] by the invariant. They are also shorter than h, since they were popped as shorter or were hidden behind something shorter. So i sees j.
Nothing deeper is visible. For any entry m below j, person j stands between i and m with heights[j] >= h >= min(h, heights[m]). Therefore j blocks m.
Popping is safe. Once a person k is popped because heights[k] < h, person i stands between k and anyone further left, and h > heights[k] >= min(heights[k], anything). So i blocks k for everyone on the left. The equal-height case is similar: if heights[k] == h, then h >= min(h, g) for any g further left, so i blocks k. Removing k is correct, and it keeps the stack strictly decreasing.
Duplicates
Equal heights are the classic trap. For [5, 5, 7], person 0 sees person 1, but not person 2, because person 1 is not strictly shorter than min(5, 7) = 5. So after counting an equal-height person we must stop, and we must not also count the taller person behind them. A solution that pops with <= and then also counts the next stack entry over-counts here (it would give 2 for the first person).
Walkthrough on [10, 6, 8, 5, 11, 9]
| i | h | popped (counted) | top counted | ans[i] | stack after push (bottom to top) |
|---|---|---|---|---|---|
| 5 | 9 | none | stack empty | 0 | [9] |
| 4 | 11 | 9 | stack empty | 1 | [11] |
| 3 | 5 | none | 11 | 1 | [11, 5] |
| 2 | 8 | 5 | 11 | 2 | [11, 8] |
| 1 | 6 | none | 8 | 1 | [11, 8, 6] |
| 0 | 10 | 6, 8 | 11 | 3 | [11, 10] |
Result: [3, 1, 2, 1, 1, 0].
Complexity
- Time: O(n). Each index is pushed once and popped at most once. The inner
whileloop is amortized constant per element. - Space: O(n) for the stack (worst case, a strictly decreasing input), plus O(n) for the output.
The brute force scans right from each person while tracking the running maximum of the people in between. That is O(n²), around 10^10 operations at n = 100000, which is too slow.
Code (Python)
from typing import List
def visible_counts(heights: List[int]) -> List[int]:
n = len(heights)
ans = [0] * n
stack: List[int] = [] # strictly decreasing from bottom to top
for i in range(n - 1, -1, -1):
h = heights[i]
count = 0
# Strictly shorter people: visible now, hidden from everyone further left.
while stack and stack[-1] < h:
stack.pop()
count += 1
# First person at least as tall: visible, but nothing beyond is.
if stack:
count += 1
if stack[-1] == h:
stack.pop() # equal height is hidden behind i from the left
ans[i] = count
stack.append(h)
return ans
if __name__ == "__main__":
print(visible_counts([10, 6, 8, 5, 11, 9])) # [3, 1, 2, 1, 1, 0]
print(visible_counts([5, 5, 7])) # [1, 1, 0]
print(visible_counts([5, 5, 5])) # [1, 1, 0]
Edge cases
n = 1: the answer is[0].- The last person always gets 0.
- All equal, e.g.
[5, 5, 5]: each person sees only their right neighbor, so the answer is[1, 1, 0]. - Strictly increasing, e.g.
[1, 2, 3]: each person sees only the next one, giving[1, 1, 0]. The stack never holds more than one entry. - Strictly decreasing, e.g.
[3, 2, 1]: each person sees only the next one, giving[1, 1, 0]. The stack grows to sizen. - Large values up to 10^9 are not an issue, since we only compare them.
Common mistakes
- Handling only distinct heights and getting duplicates wrong.
- Popping the equal-height entry but then also counting the taller one beneath it.
- Forgetting to count the first blocking person, which is visible even though it ends the view.
- Scanning left to right and trying to patch counts afterward, which complicates the logic without benefit.
- Claiming O(n) without the push-once, pop-once argument.