call(back)
Algorithms & Data StructuresmediumSign in to star problems

Escape-Room Leaderboard

Design EscapeRoomGame for a fixed set of players moving through rooms 0..R. All players start in room 0. Their initial tie order is the order of the constructor's player list.

advance(player_id)     -> None   move the player forward one room. O(1).
                                 A player already in room R stays there.
get_room(player_id)    -> int    the player's current room. O(1).
leaderboard(k)         -> list   up to k player ids ordered by
                                 room DESC, ties broken by EARLIEST
                                 entry into that room.  Must be O(N + k),
                                 NOT O(N log N) - no sorting per query.

Example

g = EscapeRoomGame([7, 3, 9], R=2)
g.leaderboard(3)  -> [7, 3, 9]        # all in room 0, constructor order
g.advance(3); g.advance(9)
g.leaderboard(2)  -> [3, 9]           # both in room 1, 3 entered first
g.advance(9)
g.leaderboard(3)  -> [9, 3, 7]

Constraints: 1 <= N <= 1e5 players, ids unique in [0, 1e9]; 1 <= R <= 1e4; up to 2e5 operations; 1 <= k <= N.

Hints

Hint 1

One doubly-linked list per room, exactly the LRU-cache trick: advance() unlinks a node and appends it to the next room's tail

Hint 2

leaderboard() walks rooms from the highest occupied one down. No sorting, no heap.

Asked at