1912. Design Movie Rental System LeetCode Solution

In this guide, you will get 1912. Design Movie Rental System LeetCode Solution with the best time and space complexity. The solution to Design Movie Rental System problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Design Movie Rental System solution in C++
  4. Design Movie Rental System solution in Java
  5. Design Movie Rental System solution in Python
  6. Additional Resources
1912. Design Movie Rental System LeetCode Solution image

Problem Statement of Design Movie Rental System

You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array entries where entries[i] = [shopi, moviei, pricei] indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. Each shop carries at most one copy of a movie moviei.
The system should support the following functions:

Search: Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopi should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.
Rent: Rents an unrented copy of a given movie from a given shop.
Drop: Drops off a previously rented copy of a given movie at a given shop.
Report: Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res where res[j] = [shopj, moviej] describes that the jth cheapest rented movie moviej was rented from the shop shopj. The movies in res should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopj should appear first, and if there is still tie, the one with the smaller moviej should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned.

Implement the MovieRentingSystem class:

MovieRentingSystem(int n, int[][] entries) Initializes the MovieRentingSystem object with n shops and the movies in entries.
List search(int movie) Returns a list of shops that have an unrented copy of the given movie as described above.
void rent(int shop, int movie) Rents the given movie from the given shop.
void drop(int shop, int movie) Drops off a previously rented movie at the given shop.
List<List> report() Returns a list of cheapest rented movies as described above.

Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie.

Example 1:

Input
[“MovieRentingSystem”, “search”, “rent”, “rent”, “report”, “drop”, “search”]
[[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]]
Output
[null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]]

Explanation
MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]);
movieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.
movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3].
movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1].
movieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.
movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2].
movieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.

Constraints:

1 <= n <= 3 * 105
1 <= entries.length <= 105
0 <= shopi < n
1 <= moviei, pricei <= 104
Each shop carries at most one copy of a movie moviei.
At most 105 calls in total will be made to search, rent, drop and report.

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(n + |\texttt{rent()}|)

1912. Design Movie Rental System LeetCode Solution in C++

class MovieRentingSystem {
 public:
  MovieRentingSystem(int n, vector<vector<int>>& entries) {
    for (const vector<int>& e : entries) {
      const int shop = e[0];
      const int movie = e[1];
      const int price = e[2];
      unrented[movie].insert({price, shop});
      shopAndMovieToPrice[{shop, movie}] = price;
    }
  }

  vector<int> search(int movie) {
    vector<int> ans;
    int i = 0;

    for (const auto& [price, shop] : unrented[movie]) {
      ans.push_back(shop);
      if (++i >= 5)
        break;
    }

    return ans;
  }

  void rent(int shop, int movie) {
    const int price = shopAndMovieToPrice[{shop, movie}];
    unrented[movie].erase({price, shop});
    rented.insert({price, {shop, movie}});
  }

  void drop(int shop, int movie) {
    const int price = shopAndMovieToPrice[{shop, movie}];
    unrented[movie].insert({price, shop});
    rented.erase({price, {shop, movie}});
  }

  vector<vector<int>> report() {
    vector<vector<int>> ans;
    int i = 0;

    for (const auto& [_, shopAndMovie] : rented) {
      ans.push_back({shopAndMovie.first, shopAndMovie.second});
      if (++i >= 5)
        break;
    }

    return ans;
  }

 private:
  struct PairHash {
    size_t operator()(const pair<int, int>& p) const {
      return p.first ^ p.second;
    }
  };

  // {movie: (price, shop)}
  unordered_map<int, set<pair<int, int>>> unrented;

  // {(shop, movie): price}
  unordered_map<pair<int, int>, int, PairHash> shopAndMovieToPrice;

  // (price, (shop, movie))
  set<pair<int, pair<int, int>>> rented;
};
/* code provided by PROGIEZ */

1912. Design Movie Rental System LeetCode Solution in Java

class MovieRentingSystem {
  public MovieRentingSystem(int n, int[][] entries) {
    for (int[] e : entries) {
      final int shop = e[0];
      final int movie = e[1];
      final int price = e[2];
      unrented.putIfAbsent(movie, new TreeSet<>(comparator));
      unrented.get(movie).add(new Entry(price, shop, movie));
      shopAndMovieToPrice.put(new Pair<>(shop, movie), price);
    }
  }

  public List<Integer> search(int movie) {
    return unrented.getOrDefault(movie, Collections.emptySet())
        .stream()
        .limit(5)
        .map(e -> e.shop)
        .collect(Collectors.toList());
  }

  public void rent(int shop, int movie) {
    final int price = shopAndMovieToPrice.get(new Pair<>(shop, movie));
    unrented.get(movie).remove(new Entry(price, shop, movie));
    rented.add(new Entry(price, shop, movie));
  }

  public void drop(int shop, int movie) {
    final int price = shopAndMovieToPrice.get(new Pair<>(shop, movie));
    unrented.get(movie).add(new Entry(price, shop, movie));
    rented.remove(new Entry(price, shop, movie));
  }

  public List<List<Integer>> report() {
    return rented.stream().limit(5).map(e -> List.of(e.shop, e.movie)).collect(Collectors.toList());
  }

  private record Entry(int price, int shop, int movie) {}

  private Comparator<Entry> comparator = (a, b) -> {
    if (a.price != b.price)
      return Integer.compare(a.price, b.price);
    if (a.shop != b.shop)
      return Integer.compare(a.shop, b.shop);
    return Integer.compare(a.movie, b.movie);
  };

  // {movie: (price, shop)}
  private Map<Integer, Set<Entry>> unrented = new HashMap<>();

  // {(shop, movie): price}
  private Map<Pair<Integer, Integer>, Integer> shopAndMovieToPrice = new HashMap<>();

  // (price, shop, movie)
  private Set<Entry> rented = new TreeSet<>(comparator);
}
// code provided by PROGIEZ

1912. Design Movie Rental System LeetCode Solution in Python

from sortedcontainers import SortedList


class MovieRentingSystem:
  def __init__(self, n: int, entries: list[list[int]]):
    self.unrented = collections.defaultdict(
        SortedList)  # {movie: (price, shop)}
    self.shopAndMovieToPrice = {}  # {(shop, movie): price}
    self.rented = SortedList()  # (price, shop, movie)
    for shop, movie, price in entries:
      self.unrented[movie].add((price, shop))
      self.shopAndMovieToPrice[(shop, movie)] = price

  def search(self, movie: int) -> list[int]:
    return [shop for _, shop in self.unrented[movie][:5]]

  def rent(self, shop: int, movie: int) -> None:
    price = self.shopAndMovieToPrice[(shop, movie)]
    self.unrented[movie].remove((price, shop))
    self.rented.add((price, shop, movie))

  def drop(self, shop: int, movie: int) -> None:
    price = self.shopAndMovieToPrice[(shop, movie)]
    self.unrented[movie].add((price, shop))
    self.rented.remove((price, shop, movie))

  def report(self) -> list[list[int]]:
    return [[shop, movie] for _, shop, movie in self.rented[:5]]
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.