I knew the one-directional version of this problem so my first instinct was to just write that and call it done.
Use a monotonic stack to efficiently compute the number of visible people to the left and right for each person. For each direction, maintain a stack of indices with heights in decreasing order, popping shorter people and counting them as visible, then add the top of the stack if it exists. Sum the counts from both directions to get the total for each person.
Pro tip: Clarify that the visibility condition is equivalent to finding the nearest greater element in each direction, but with the nuance that all shorter people between are also visible. Emphasize that the monotonic stack approach handles this in O(n) time, which is optimal.
Restate the problem: for each person, count how many people they can see to the left and right. A person can see another if everyone between them is shorter than the shorter of the two. Confirm with the interviewer that the array has distinct heights.
For the left-to-right pass, use a stack that stores indices of people in decreasing order of height. For each person, pop all shorter people from the stack (each popped person is visible), then if the stack is not empty, the top person is also visible (since they are taller). Push the current person onto the stack.
Repeat the process from right to left to count visible people on the right side. Use a separate stack and accumulate the counts into a result array.
Sum the left and right counts for each person. Consider edge cases: empty array, single person, strictly increasing or decreasing heights. Ensure the algorithm runs in O(n) time and O(n) space.
Explain that each person is pushed and popped at most once per direction, so total time is O(n). Walk through a small example (e.g., [3,1,2]) to verify correctness and discuss potential pitfalls.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.