Towers stand in a row with heights heights[i]. Each sends one message right, landing on the first tower to its right that is at least as tall; otherwise it's lost.
Write messages_received(heights: list[int]) -> list[int] that returns how many messages each tower receives.
messages_received([3, 1, 2, 5, 4, 5]) # [0, 0, 1, 2, 0, 2]
# tower 0 (3) -> tower 3 (5)
# tower 1 (1) -> tower 2 (2)
# tower 2 (2) -> tower 3 (5)
# tower 3 (5) -> tower 5 (5) equal height counts
# tower 4 (4) -> tower 5 (5)
# tower 5 (5) -> lost
messages_received([4, 4, 4]) # [0, 1, 1]
Up to 2 * 10^5 towers. ⭐ Bonus: a speed test earns a star in O(n).
Show hint
sweep left to right with a stack of towers still waiting. Each new tower pops every waiting tower no taller than itself: one message per pop.