#1912

Design Movie Rental System

Hard
ArrayHash TableDesignHeap (Priority Queue)Ordered SetHash MapPriority Queue
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

By using a combination of data structures like a HashMap for storing available movies and a priority queue for managing rented movies, we can efficiently handle searching, renting, and reporting with better performance.

⚙️

Algorithm

5 steps
  1. 1Step 1: Use a HashMap to store available movies with their prices and shops.
  2. 2Step 2: Use a priority queue (min-heap) to manage rented movies sorted by price.
  3. 3Step 3: For searching, retrieve from the HashMap and maintain a sorted list of available movies.
  4. 4Step 4: For renting, remove the movie from the HashMap and add it to the priority queue.
  5. 5Step 5: For dropping, move the movie back to the HashMap and adjust the priority queue.
solution.py33 lines
1# Full working Python code
2import heapq
3class MovieRentalSystem:
4    def __init__(self, entries):
5        self.available = {}
6        self.rented = []
7        for shop, movie, price in entries:
8            if movie not in self.available:
9                self.available[movie] = []
10            heapq.heappush(self.available[movie], (price, shop))
11
12    def search(self, movie):
13        if movie not in self.available:
14            return []
15        return sorted(self.available[movie])[:5]
16
17    def rent(self, shop, movie):
18        if movie in self.available and self.available[movie]:
19            price, available_shop = heapq.heappop(self.available[movie])
20            if available_shop == shop:
21                heapq.heappush(self.rented, (price, shop, movie))
22            else:
23                heapq.heappush(self.available[movie], (price, available_shop))
24
25    def drop(self, shop, movie):
26        for i in range(len(self.rented)):
27            if self.rented[i][1] == shop and self.rented[i][2] == movie:
28                price, _, _ = self.rented.pop(i)
29                heapq.heappush(self.available[movie], (price, shop))
30                return
31
32    def report(self):
33        return sorted(self.rented)[:5]

Complexity note: The time complexity is O(n log n) due to the use of priority queues for managing the rented movies and the sorting of available movies. The space complexity is O(n) because we store all the movies and rented entries.

  • 1Using priority queues can significantly improve the efficiency of searching and managing rented movies.
  • 2Maintaining a HashMap allows for quick access to available movies, reducing the time complexity of searches.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.