Problem Description
Design a movie rental system for n shops where each shop holds at most one copy of a movie. You must support four operations:
- Search – Given a movie id, return the cheapest 5 shops (sorted by price, then shop id) that have an unrented copy.
- Rent – Rent an unrented copy of a movie from a given shop.
- Drop – Return a previously rented movie to its shop.
- Report – Return the cheapest 5 currently rented movies (sorted by price, then shop id, then movie id).
Key Insights
- We need to maintain two views of the data: one sorted by movie (for available copies) and another global view (for rented movies).
- For each movie id, use an ordered data structure (balanced BST, TreeSet, or sorted list with binary search) to quickly extract the cheapest unrented shops.
- Use another global ordered data structure for all rented movies, sorting by price, then shop, then movie.
- Each operation (search, rent, drop, report) affects only one or both of these data structures via insertion or deletion.
- Data structures like TreeSet in Java or std::set in C++ can offer O(log n) insertion/deletion and retrieval of the top k items.
Space and Time Complexity
Time Complexity:
- Search, rent, drop, and report operations take O(log n) per insertion/deletion and O(k) for returning top k (with k ≤ 5) elements. Space Complexity:
- O(m) where m is the number of entries, for storing available and rented movie records.
Solution
The solution uses two core data structures:
- A mapping from movie id to an ordered set (or sorted list) of available copies, each represented as a tuple (price, shop). This allows us to quickly search for the cheapest available shops for a given movie.
- A global ordered set (or sorted list) for rented movies, each represented as a tuple (price, shop, movie) to support the report operation in the required order. Additionally, a mapping (or hash table) from (shop, movie) pair to price helps to lookup prices for updates.
Operations are handled as follows:
- Search(movie): Lookup the ordered set for the movie and return up to 5 shop ids from the beginning.
- Rent(shop, movie): Remove the corresponding (price, shop) tuple from the movie’s available set, then insert (price, shop, movie) into the global rented set.
- Drop(shop, movie): Remove the corresponding (price, shop, movie) tuple from the rented set and add back (price, shop) into the movie’s available set.
- Report(): Return the first 5 entries (shop, movie) from the global rented set.