Design a waitlist manager
GoogleSoftware Engineer · OnsiteLast updated
This question tests your ability to design a waitlist system using efficient data structures to handle insertions, removals, and lookup operations.
Design a Waitlist Manager
Design a WaitlistManager class that maintains a list of parties waiting for a table at a restaurant. Each party is represented by a unique party_id (integer) and the number of people in the party.
You need to implement the following methods:
add_party(party_id, num_people): Adds a new party to the end of the waitlist. If theparty_idalready exists, returnFalse. Otherwise, add them and returnTrue.seat_party(party_id): Removes the party from the waitlist because they have been seated. If theparty_idis not in the waitlist, returnFalse. Otherwise, returnTrue.get_position(party_id): Returns the current position (1-indexed) of the party in the queue. If theparty_idis not in the waitlist, return-1.get_next_party(): Returns theparty_idof the party at the front of the queue, or-1if the waitlist is empty.
Constraints
party_idis a unique positive integer.- The number of operations can be up to 10^5.
get_positionshould be faster than O(n).
Example
manager = WaitlistManager()
manager.add_party(101, 4) # Returns True
manager.add_party(102, 2) # Returns True
manager.get_position(102) # Returns 2
manager.seat_party(101) # Returns True
manager.get_position(102) # Returns 1
Hints
Hint 1
A standard queue allows for O(1) access to the front, but finding a party in the middle or their position would take O(n).
Hint 2
Consider using a combination of a Doubly Linked List to maintain order and a Hash Map to store references to nodes for O(1) lookup.
Hint 3
For the position, you could store an index in the hash map, but remember that removing a party from the middle of the list will require updating the positions of all subsequent parties.
Follow-up questions
- How would you modify the system if a party could change their group size while waiting?
- If the waitlist grows to millions of users, how would you persist this data in a database while keeping the API performant?
- What if you need to prioritize parties based on their wait time or a VIP status; what data structure would be most appropriate?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.