KatInterview

Dynamic Room Occupancy Tracker with Top-K Ranking Query

Data Structure DesignModel answer
HardModel answerData Structure Designdesign-dsheaps-sortinghash-map

Last 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.
  • 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_rooms must 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.