Python coding

How many people each person can see

People stand in a line, all facing right, and heights[i] is the height of person i; no two heights are equal. Person i can see person j > i when everyone standing between them is shorter than both of them. Return how many people each person can see. For [10, 6, 8, 5, 11, 9] the answer is [3, 1, 2, 1, 1, 0]: the first person sees 6, 8 and 11, but not 5 (8 is in the way) or 9 (11 is).

heights may be empty; heights are distinct positive integers. Aim for O(n): checking every pair is O(n²).

Besides the tests, one large input (7,000 people) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • visible_counts([10,6,8,5,11,9]) → [3,1,2,1,1,0]
  • visible_counts([5,1,2,3,10]) → [4,1,1,1,0]
  • visible_counts([3,2,1]) → [1,1,0]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Scan from the right and keep a stack of the people that someone further left could still see. Their heights grow from the top of the stack down.

Hint 2

Person i sees every shorter person they pop, and from then on i hides them from everyone further left. If someone is left on the stack, i also sees that first taller person.

Solution and why it works
pythonO(n) · O(n)
def visible_counts(heights: list[int]) -> list[int]:
    answer, stack = [0] * len(heights), []   # stack: heights still in view, shortest on top
    for i in range(len(heights) - 1, -1, -1):
        h = heights[i]
        while stack and stack[-1] < h:
            stack.pop()                      # i sees them, and hides them from the left
            answer[i] += 1
        if stack:
            answer[i] += 1                   # the first taller person: seen, blocks the rest
        stack.append(h)
    return answer

Scanning from the right, the stack holds the people still in view from the left, shortest on top. Person i sees each shorter person they pop: anyone between them taller than that person would have popped them already. Once popped, they stay hidden behind i. The first taller person left on the stack is seen too, and blocks everyone behind them. Each person is pushed and popped once: O(n). The trap is forgetting that taller person, or counting past them.