progress

~/problems / Stacks / Monotonic stack

Messages between signal towers

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

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
Six towers of heights 3, 1, 2, 5, 4, 5; each message arcs to the first tower to its right that is at least as tall, so towers 3 and 5 each receive 2 messages, tower 2 receives 1, and the last tower's message is 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.

Topic: Monotonic stack. Next greater/smaller element in O(n); histogram rectangles; trapping water.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc