[
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.shops
is dictionary: for every movie we keep sorted list of tuples(price, shop)
.self.shop_movie
is dictionary, which allows us to answer what is price, given shop and movie.self.rented
is 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.shops
andself.shop_movie
. We keepself.rented
empty, because we did not rent any movies yet.search(movie)
: we go through first5
elements ofself.shops[movie]
and return prices.rent(shop, movie)
: first, we find price, using ourself.shop_movie
dictionary 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.report
Here we look atself.rented
and take5
cheapes movies, that is5
first 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]]