The visibility rule tripped me up at first.
Use a monotonic decreasing stack to efficiently compute visible people to the right for each person. Iterate from right to left, maintaining a stack of indices with heights in decreasing order, and for each person, pop shorter people while counting them as visible, then if the stack is not empty, the top person is also visible (if taller or equal).
Pro tip: Clarify the visibility condition: if two people have the same height, they can see each other only if no one taller or equal is between them. In the stack approach, when encountering equal height, you should pop and count them as visible, then stop because the next person in stack would be taller and block further visibility.
Restate the problem in your own words: For each person, count how many people to their right are visible, where visibility is blocked by anyone of height >= the shorter of the two.
Decide to use a stack to keep track of potential visible people. The stack will store indices of people in decreasing order of height from bottom to top.
For each person i from n-1 down to 0, pop from stack while stack top height < current height, counting each popped as visible. If stack not empty after popping, the top person is visible (since they are taller or equal), so increment count. Then push current index onto stack.
When encountering equal height, pop and count them as visible, but then stop because the next person in stack would be taller and block further visibility. This ensures correct handling of duplicates.
Explain that each person is pushed and popped at most once, so time complexity is O(n) and space complexity is O(n) for the stack.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.