[
bst
design
heap
]
Leetcode 1912. Design Movie Rental System
Problem statement
https://leetcode.com/problems/design-movie-rental-system/
Solution
This is a problem with quite heavy statement, but in fact it can be solved pretty strarightforward using SortedList library in python. The idea is to keep several pieces of information:
self.shopsis dictionary: for every movie we keep sorted list of tuples(price, shop).self.shop_movieis dictionary, which allows us to answer what is price, given shop and movie.self.rentedis SortedList of rented movies so far.
Now, lwt us go through our functions and check how they work:
_ _init_ _: here we create empty objects, and then fillself.shopsandself.shop_movie. We keepself.rentedempty, because we did not rent any movies yet.search(movie): we go through first5elements ofself.shops[movie]and return prices.rent(shop, movie): first, we find price, using ourself.shop_moviedictionary and then remove this movie from given shop and add it to rented.drop(shop, movie): very similar to previous one, now we add movie back to shop and remove it from rented.reportHere we look atself.rentedand take5cheapes movies, that is5first elements.
Complexity
_ _ init _ _: time isO(n log n), space isO(n).search(movie): time isO(log n), space isO(1).rent(shop, movie): time isO(log n), additional space isO(1).drop(shop, movie): time isO(log n), additional space isO(1).report: time isO(log n), space isO(1).
Code
from sortedcontainers import SortedList
class MovieRentingSystem:
def __init__(self, n, entries):
self.shops = defaultdict(SortedList) #movie -> (price, shop)
self.shop_movie = {} #(shop, movie) -> price
self.rented = SortedList() # (price, shop, movie)
for s, m, p in entries:
self.shops[m].add((p, s))
self.shop_movie[s, m] = p
def search(self, movie):
return [y for _,y in self.shops[movie][:5]]
def rent(self, shop, movie):
price = self.shop_movie[shop, movie]
self.shops[movie].remove((price, shop))
self.rented.add((price, shop, movie))
def drop(self, shop, movie):
price = self.shop_movie[shop, movie]
self.shops[movie].add((price, shop))
self.rented.remove((price, shop, movie))
def report(self):
return [[y,z] for _,y,z in self.rented[:5]]