~/problems / Heaps / Heaps and priority queues

OA: Escape room leaderboard

medium 2 levels ~40 min Pinterest

Level 1 Rooms, head counts and the leader

An escape-room venue chains n puzzle rooms in a line, numbered 0 to n - 1. A game has m players, numbered 0 to m - 1, who all start in room 0. Each player works alone: when they crack their current room's puzzle they walk into the next room, and cracking room n - 1 means they have escaped. We track an escaped player as being in position n.

The venue wants a live scoreboard. Implement class EscapeRoomLeaderboard:

  • EscapeRoomLeaderboard(n: int, m: int): n rooms and m players, everyone in room 0.
  • advance(player: int) -> int: player solves the puzzle in front of them and moves on by one. Return their new position (n once they escape). Advancing a player who has already escaped changes nothing and returns n.
  • count_in_room(r: int) -> int: how many players are in position r right now, for 0 <= r <= n (r == n counts escaped players).
  • leader() -> int: the player currently in first place.

Ranking. A player is ahead of another if their position is higher. On equal positions, whoever reached that position earlier (an earlier successful advance call) is ahead. Players still in room 0 have never arrived anywhere, so among them the smaller player number is ahead.

lb = EscapeRoomLeaderboard(3, 4)   # rooms 0, 1, 2; players 0..3
lb.leader()           # 0   (everyone in room 0, lowest number wins)
lb.advance(2)         # 1
lb.advance(1)         # 1
lb.leader()           # 2   (both in room 1, but player 2 got there first)
lb.advance(1)         # 2
lb.leader()           # 1
lb.count_in_room(0)   # 2   (players 0 and 3)
lb.advance(1)         # 3   (escaped)
lb.advance(1)         # 3   (already out; nothing changes)
lb.count_in_room(3)   # 1

Constraints: 1 <= n, m <= 10^5, up to 2 * 10^5 calls in total, all arguments valid. count_in_room must be O(1) and leader must not scan all players; a leaderboard that re-sorts or scans on every query is the classic mistake here.

Show hint

A head-count array handles count_in_room. For leader, think of a heap you push to on every move; a player's older entries go stale, so consider lazy deletion instead of removing them.

Level 2 unlocks when level 1 passes.

Topic: Heaps and priority queues. heapq: top-k, k-way merge, two heaps for a running median.

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