Gamified challenge · Hash maps
A valet lot has capacity spaces and receives ops, a list of requests. "park P T" parks car P with ticket T; if car P is already in the lot, its ticket becomes T instead. "fetch P" asks for car P's ticket: the answer is the ticket, or -1 if the car isn't in the lot (the car stays parked). Both requests count as using the car.
When a new car arrives and the lot is full, first tow the least recently used car (the one whose last park or fetch is oldest). Write simulate(capacity, ops) that returns the answers to the fetches, in order. Every request must be handled in O(1) on average: think hash map plus doubly linked list.
With capacity = 2 and ["park 1 10", "park 2 20", "fetch 1", "park 3 30", "fetch 2"] the answer is [10, -1]: fetching car 1 made car 2 the least recently used, so car 3's arrival got car 2 towed.
This game is part of the paid plans. Sign in, then pick a plan to write your answer, watch it play out, and step through the algorithm with its guide.
Sign in with Google