Dynamic Room Occupancy Tracker with Top-K Ranking Query
Data Structure DesignModel answerLast updated
Design an in-memory system tracking occupancy and entry times across rooms, returning the busiest rooms in optimal logarithmic time per update.
Design an operational tracking system for a multi-room facility that processes occupant movements in real time and efficiently answers top-$k$ busiest room queries.
Implement the class OccupancyTracker:
add_person(person_id: str, room_id: str) -> None: Registers a person entering a room.- Inputs and time are governed by a global monotonically increasing clock that advances by $1$ on every call to
add_person. - If the person is currently present in another room (or even the same room), they must exit that room first before entering the new one.
- Re-entering updates their arrival time to the current timestamp.
- Inputs and time are governed by a global monotonically increasing clock that advances by $1$ on every call to
leave_room(person_id: str) -> None: Removes a person from their current room. If the person is not currently in any room, this operation is a no-op.get_top_k_rooms(k: int) -> List[str]: Retrieves the top $k$ busiest non-empty rooms.- Primary criteria: Rooms with higher occupant counts rank first.
- Secondary criteria (tie-breaker): If two rooms have equal occupant counts, prioritize the room whose most recently arrived current occupant arrived earlier (i.e., smaller arrival timestamp).
- Returns up to $k$ room IDs in descending order of precedence. Empty rooms are excluded.
Constraints
- Total distinct occupants $N \le 10^5$.
- Total distinct rooms $M \le 10^4$.
- Operations are called dynamically in any sequence.
get_top_k_roomsmust run faster than $O(M \log M)$ per query.
Example
tracker = OccupancyTracker()
tracker.add_person("p1", "R1") # t=1: R1 has 1 person (latest arrival t=1)
tracker.add_person("p2", "R2") # t=2: R2 has 1 person (latest arrival t=2)
tracker.add_person("p3", "R1") # t=3: R1 has 2 people (latest arrival t=3)
# R1 has count 2, latest t=3
# R2 has count 1, latest t=2
assert tracker.get_top_k_rooms(2) == ["R1", "R2"]
Hints
Hint 1
Use a global hash map to locate which room an occupant is currently in so departures and transfers run in O(1) map operations.
Hint 2
Maintain an insertion-ordered dictionary (or double-ended queue) per room to track occupants in arrival order. The most recent arrival is always at the tail.
Hint 3
Maintain a balanced search tree or indexed skip-list holding (-occupant_count, latest_arrival_timestamp, room_id) keys so top-k queries slice the top k elements in logarithmic time per mutation.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
To satisfy the performance constraints—specifically executing get_top_k_rooms faster than $O(M \log M)$—we must maintain state dynamically rather than sorting all rooms on query execution.
We need to maintain three core state components:
person_to_room(Hash Map): Mapsperson_idto their currentroom_id. This enables $O(1)$ lookup when a person leaves or moves.room_occupants(Hash Map of Ordered Collections): Mapsroom_idto an ordered collection of{person_id: arrival_time}. Because arrival timestamps are strictly increasing globally, inserting a person naturally appends them to the end of this mapping. In Python 3.7+, standard dictionaries preserve insertion order. Accessing the latest arrival is an $O(1)$ lookup at the end (next(reversed(dict))). Deleting an exiting occupant from the dictionary is also $O(1)$.room_ranking(Balanced Binary Search Tree / Red-Black Tree): Stores composite tuple keys representing room priorities: $$\text{Key} = (-\text{occupant_count}, \text{latest_arrival_time}, \text{room_id})$$ Sorting this structure in ascending order places the busiest rooms at the beginning. If counts are tied, smallerlatest_arrival_timevalues (earlier arrivals) appear first.
Mutation Pattern: Detach / Mutate / Attach
Whenever a room's state is modified (via addition or removal of an occupant):
- Detach: If the room is currently registered in
room_ranking, calculate its existing tuple key and remove it from the set. - Mutate: Update
room_occupantsandperson_to_room. - Attach: If the room is still non-empty, construct its new tuple key based on its updated occupant count and new latest arrival time, then insert it into
room_ranking.
This guarantees that room_ranking contains exactly one valid key per non-empty room at all times.
Python Code
from sortedcontainers import SortedList
class OccupancyTracker:
def __init__(self):
self.time = 0
self.person_to_room = {} # person_id -> room_id
self.room_occupants = {} # room_id -> Dict[person_id, arrival_time]
self.room_ranking = SortedList() # Set of (-count, latest_arrival, room_id)
def _get_room_key(self, room_id: str):
occupants = self.room_occupants.get(room_id)
if not occupants:
return None
# In an insertion-ordered dict, the last key corresponds to the most recent arrival
latest_person = next(reversed(occupants))
latest_time = occupants[latest_person]
return (-len(occupants), latest_time, room_id)
def _detach(self, room_id: str):
key = self._get_room_key(room_id)
if key is not None:
self.room_ranking.remove(key)
def _attach(self, room_id: str):
key = self._get_room_key(room_id)
if key is not None:
self.room_ranking.add(key)
def add_person(self, person_id: str, room_id: str) -> None:
self.time += 1
# If person is already in a room, handle their departure first
if person_id in self.person_to_room:
self.leave_room(person_id)
# Detach room prior to modifying state
self._detach(room_id)
# Update room occupants map
if room_id not in self.room_occupants:
self.room_occupants[room_id] = {}
self.room_occupants[room_id][person_id] = self.time
self.person_to_room[person_id] = room_id
# Re-attach room with updated metrics
self._attach(room_id)
def leave_room(self, person_id: str) -> None:
if person_id not in self.person_to_room:
return
room_id = self.person_to_room.pop(person_id)
# Detach room prior to modification
self._detach(room_id)
# Remove occupant from room map
occupants = self.room_occupants[room_id]
del occupants[person_id]
# Clean up empty room entry
if not occupants:
del self.room_occupants[room_id]
# Re-attach if still non-empty
self._attach(room_id)
def get_top_k_rooms(self, k: int) -> list[str]:
if k <= 0:
return []
# Retrieve slice of the top min(k, len) entries
return [entry[2] for entry in self.room_ranking.islice(0, k)]
Complexity Analysis
-
Time Complexity:
add_person: $O(\log M)$, where $M$ is the number of active non-empty rooms. Deleting and re-inserting an element in a balanced BST (SortedList) takes logarithmic time. Map updates take $O(1)$ average time.leave_room: $O(\log M)$ for deleting and re-inserting the room's key inSortedList.get_top_k_rooms(k): $O(\log M + k)$ to slice the top $k$ elements fromSortedList. This significantly outperforms naive $O(M \log M)$ sorting.
-
Space Complexity: $O(N + M)$ total auxiliary memory, where $N$ is the number of active occupants and $M$ is the number of active rooms.
Common Pitfalls & Edge Cases
- Re-adding an existing person: Forgetting to remove a person from their current room prior to adding them to a new room causes duplicate entries and inaccurate occupant counts.
- Re-adding to the same room: If
add_person("p1", "R1")is called whenp1is already inR1, the person must be treated as leaving and re-entering, updating their arrival timestamp to the new global clock time. - Empty Rooms: Once an occupant leaves and a room count drops to zero, the room key must be completely evicted from
room_ranking. - Tie-Breaker Inversion: Ensure primary sorting is descending (handled via
-count) while secondary sorting is ascending (handled via positivelatest_time).