Room Assignment and Leaderboard for Streaming Sessions
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a stream of operations that assigns sessions to the lowest-numbered free room and reports the top-k streams by total duration, tested with heaps and lazy deletion.
Room Assignment and Leaderboard
A platform runs live streaming sessions in virtual rooms and keeps a leaderboard of the streams that have been on air the longest. You are given a log of operations to replay, in order, and you must return the result of each one.
Operations
Two parallel lists describe the log. ops[i] is the name of the i-th operation and op_args[i] holds its arguments.
"schedule" with arguments [start, end, stream_id]
- A session occupies the half-open interval
[start, end). - Place it in the free room with the smallest room ID. Rooms are numbered from 0.
- A room is free at time
startif the session it last hosted ended at or beforestart. A session ending at 5 therefore frees its room for a session starting at 5. - If no existing room is free, open a new room. Its ID equals the number of rooms created so far.
- The result of this operation is the room ID used.
- The session adds
end - startto the running total forstream_id.
"top_k_streams" with arguments [k]
- Rank every stream seen so far by its total accumulated duration, largest first.
- Streams with equal totals are ordered alphabetically by
stream_id. - The result is the list of the first
kstream IDs in that order. - If fewer than
kdistinct streams exist, return all of them in ranked order. If there are none, return[].
Your task
Implement process_session_log(ops, op_args). It returns a list with one entry per operation, in the same order. Each entry is an int for "schedule" or a list[str] for "top_k_streams".
Constraints
len(ops) == len(op_args)and is at most10^5.- For
"schedule":0 <= start < end <= 10^9. - The
startvalues of successive"schedule"operations are non-decreasing. stream_idhas length 1 to 32 and uses lowercase English letters (underscores may also appear).- For
"top_k_streams":1 <= k <= 1000. - Every operation name is either
"schedule"or"top_k_streams".
Examples
Example 1
Input: process_session_log(['schedule', 'schedule', 'schedule', 'schedule', 'top_k_streams'], [[1, 5, 'stream_a'], [2, 6, 'stream_b'], [5, 8, 'stream_c'], [7, 10, 'stream_a'], [2]])
Output: [0, 1, 0, 1, ['stream_a', 'stream_b']]
Example 2
Input: process_session_log(['schedule', 'schedule', 'top_k_streams', 'schedule', 'top_k_streams'], [[0, 10, 'z'], [0, 10, 'a'], [3], [10, 12, 'a'], [2]])
Output: [0, 1, ['a', 'z'], 0, ['a', 'z']]
Hints
Hint 1
Treat room assignment and the leaderboard as two independent problems that share one input log.
Hint 2
For rooms, keep one min-heap of (end_time, room_id) for busy rooms and another min-heap of idle room IDs. Before each placement, move every room with end_time <= start into the idle heap.
Hint 3
For the leaderboard, totals only grow. Push (-total, stream_id) after every update and skip entries whose total no longer matches the current one when answering a query. Push the valid entries back afterwards.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The log mixes two independent problems, so we solve them side by side.
Room assignment (two min-heaps).
busy_roomsstores(end_time, room_id)for rooms currently hosting a session.idle_roomsstores the IDs of rooms that exist and are free.- On
schedule(start, end, id), first pop every busy room withend_time <= startand push its ID intoidle_rooms. The<=matches the half-open interval rule. - If
idle_roomsis non-empty, take its smallest ID. Otherwise open a new room whose ID is the count of rooms created so far. - Push
(end, room_id)ontobusy_rooms.
Leaderboard (max-heap with lazy deletion).
total_time[stream]holds each stream's accumulated duration.- After each schedule, push
(-total, stream)ontoboard. Negating the total turns Python's min-heap into "largest first", and tuple comparison breaks ties bystreamin alphabetical order, as required. - Older entries for the same stream remain in the heap but are now outdated.
- On
top_k_streams(k), pop entries untilkvalid ones are collected or the heap is empty. An entry is valid only if its total equals the currenttotal_time[stream]. Outdated entries are discarded permanently. The valid ones are pushed back so later queries still see them.
Why it is correct
- Start times never decrease, so a room that is free at time
tis free at every later start. Releasing rooms early therefore never causes a wrong choice. - After the release step,
idle_roomscontains exactly the rooms free atstart, so its minimum is the smallest available ID. A new room is opened only when none is free, and its ID equals the number of rooms created so far. - Each session has positive duration, so a stream's total strictly increases with every update. Exactly one heap entry per stream matches its current total, so there are no duplicates among valid entries.
- Valid entries leave the heap in
(-total, stream_id)order, which is the required ranking. If the heap empties beforekare found, all streams have been returned in ranked order.
Complexity
Let n be the number of operations.
scheduleis O(log n) amortized. Each session enters and leavesbusy_roomsonce, and the leaderboard push is O(log n).top_k_streamscosts O((k + s) log n), wheresis the number of outdated entries removed. Each push produces at most one outdated entry, and it is removed only once, so the total over the whole run is O(n log n) for removals plus O(k log n) per query.- Space is O(n).
Reference solution
import heapq
from typing import List
def process_session_log(ops: List[str], op_args: List[List]) -> List:
idle_rooms = [] # min-heap of idle room IDs
busy_rooms = [] # min-heap of (end_time, room_id)
rooms_created = 0
total_time = {} # stream_id -> accumulated duration
board = [] # min-heap of (-total, stream_id); may hold stale entries
output = []
for op, args in zip(ops, op_args):
if op == "schedule":
start, end, sid = args
# Release every room whose session has finished by `start`.
while busy_rooms and busy_rooms[0][0] <= start:
_, rid = heapq.heappop(busy_rooms)
heapq.heappush(idle_rooms, rid)
if idle_rooms:
rid = heapq.heappop(idle_rooms)
else:
rid = rooms_created
rooms_created += 1
heapq.heappush(busy_rooms, (end, rid))
total_time[sid] = total_time.get(sid, 0) + (end - start)
heapq.heappush(board, (-total_time[sid], sid))
output.append(rid)
elif op == "top_k_streams":
k = args[0]
kept = []
names = []
while board and len(names) < k:
neg, sid = heapq.heappop(board)
if total_time.get(sid) != -neg:
continue # outdated entry, discard for good
names.append(sid)
kept.append((neg, sid))
for item in kept:
heapq.heappush(board, item)
output.append(names)
else:
raise ValueError("unknown operation")
return output