Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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:
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.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<Integer> 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<Integer>> 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 * 1051 <= entries.length <= 1050 <= shopi < n1 <= moviei, pricei <= 104moviei.105 calls in total will be made to search, rent, drop and report.Problem summary: 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
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Design · Segment Tree
["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]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1912: Design Movie Rental System
class MovieRentingSystem {
private Map<Integer, TreeSet<int[]>> available = new HashMap<>();
private Map<Long, Integer> priceMap = new HashMap<>();
private TreeSet<int[]> rented = new TreeSet<>((a, b) -> {
if (a[0] != b[0]) {
return a[0] - b[0];
}
if (a[1] != b[1]) {
return a[1] - b[1];
}
return a[2] - b[2];
});
public MovieRentingSystem(int n, int[][] entries) {
for (int[] entry : entries) {
int shop = entry[0], movie = entry[1], price = entry[2];
available
.computeIfAbsent(movie, k -> new TreeSet<>((a, b) -> {
if (a[0] != b[0]) {
return a[0] - b[0];
}
return a[1] - b[1];
}))
.add(new int[] {price, shop});
priceMap.put(f(shop, movie), price);
}
}
public List<Integer> search(int movie) {
List<Integer> res = new ArrayList<>();
if (!available.containsKey(movie)) {
return res;
}
int cnt = 0;
for (int[] item : available.get(movie)) {
res.add(item[1]);
if (++cnt == 5) {
break;
}
}
return res;
}
public void rent(int shop, int movie) {
int price = priceMap.get(f(shop, movie));
available.get(movie).remove(new int[] {price, shop});
rented.add(new int[] {price, shop, movie});
}
public void drop(int shop, int movie) {
int price = priceMap.get(f(shop, movie));
rented.remove(new int[] {price, shop, movie});
available.get(movie).add(new int[] {price, shop});
}
public List<List<Integer>> report() {
List<List<Integer>> res = new ArrayList<>();
int cnt = 0;
for (int[] item : rented) {
res.add(Arrays.asList(item[1], item[2]));
if (++cnt == 5) {
break;
}
}
return res;
}
private long f(int shop, int movie) {
return ((long) shop << 30) | movie;
}
}
/**
* Your MovieRentingSystem object will be instantiated and called as such:
* MovieRentingSystem obj = new MovieRentingSystem(n, entries);
* List<Integer> param_1 = obj.search(movie);
* obj.rent(shop,movie);
* obj.drop(shop,movie);
* List<List<Integer>> param_4 = obj.report();
*/
// Accepted solution for LeetCode #1912: Design Movie Rental System
type MovieRentingSystem struct {
available map[int]*treeset.Set // movie -> (price, shop)
priceMap map[int64]int
rented *treeset.Set // (price, shop, movie)
}
func Constructor(n int, entries [][]int) MovieRentingSystem {
// comparator for (price, shop)
cmpAvail := func(a, b any) int {
x := a.([2]int)
y := b.([2]int)
if x[0] != y[0] {
return x[0] - y[0]
}
return x[1] - y[1]
}
// comparator for (price, shop, movie)
cmpRented := func(a, b any) int {
x := a.([3]int)
y := b.([3]int)
if x[0] != y[0] {
return x[0] - y[0]
}
if x[1] != y[1] {
return x[1] - y[1]
}
return x[2] - y[2]
}
mrs := MovieRentingSystem{
available: make(map[int]*treeset.Set),
priceMap: make(map[int64]int),
rented: treeset.NewWith(cmpRented),
}
for _, e := range entries {
shop, movie, price := e[0], e[1], e[2]
if _, ok := mrs.available[movie]; !ok {
mrs.available[movie] = treeset.NewWith(cmpAvail)
}
mrs.available[movie].Add([2]int{price, shop})
mrs.priceMap[f(shop, movie)] = price
}
return mrs
}
func (this *MovieRentingSystem) Search(movie int) []int {
res := []int{}
if _, ok := this.available[movie]; !ok {
return res
}
it := this.available[movie].Iterator()
it.Begin()
cnt := 0
for it.Next() && cnt < 5 {
pair := it.Value().([2]int)
res = append(res, pair[1])
cnt++
}
return res
}
func (this *MovieRentingSystem) Rent(shop int, movie int) {
price := this.priceMap[f(shop, movie)]
this.available[movie].Remove([2]int{price, shop})
this.rented.Add([3]int{price, shop, movie})
}
func (this *MovieRentingSystem) Drop(shop int, movie int) {
price := this.priceMap[f(shop, movie)]
this.rented.Remove([3]int{price, shop, movie})
this.available[movie].Add([2]int{price, shop})
}
func (this *MovieRentingSystem) Report() [][]int {
res := [][]int{}
it := this.rented.Iterator()
it.Begin()
cnt := 0
for it.Next() && cnt < 5 {
t := it.Value().([3]int)
res = append(res, []int{t[1], t[2]})
cnt++
}
return res
}
func f(shop, movie int) int64 {
return (int64(shop) << 30) | int64(movie)
}
/**
* Your MovieRentingSystem object will be instantiated and called as such:
* obj := Constructor(n, entries);
* param_1 := obj.Search(movie);
* obj.Rent(shop,movie);
* obj.Drop(shop,movie);
* param_4 := obj.Report();
*/
# Accepted solution for LeetCode #1912: Design Movie Rental System
class MovieRentingSystem:
def __init__(self, n: int, entries: List[List[int]]):
self.available = defaultdict(lambda: SortedList())
self.price_map = {}
for shop, movie, price in entries:
self.available[movie].add((price, shop))
self.price_map[self.f(shop, movie)] = price
self.rented = SortedList()
def search(self, movie: int) -> List[int]:
return [shop for _, shop in self.available[movie][:5]]
def rent(self, shop: int, movie: int) -> None:
price = self.price_map[self.f(shop, movie)]
self.available[movie].remove((price, shop))
self.rented.add((price, shop, movie))
def drop(self, shop: int, movie: int) -> None:
price = self.price_map[self.f(shop, movie)]
self.rented.remove((price, shop, movie))
self.available[movie].add((price, shop))
def report(self) -> List[List[int]]:
return [[shop, movie] for _, shop, movie in self.rented[:5]]
def f(self, shop: int, movie: int) -> int:
return shop << 30 | movie
# Your MovieRentingSystem object will be instantiated and called as such:
# obj = MovieRentingSystem(n, entries)
# param_1 = obj.search(movie)
# obj.rent(shop,movie)
# obj.drop(shop,movie)
# param_4 = obj.report()
// Accepted solution for LeetCode #1912: Design Movie Rental System
/**
* [1912] 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 j^th 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<Integer> 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<Integer>> 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 * 10^5
* 1 <= entries.length <= 10^5
* 0 <= shopi < n
* 1 <= moviei, pricei <= 10^4
* Each shop carries at most one copy of a movie moviei.
* At most 10^5 calls in total will be made to search, rent, drop and report.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/design-movie-rental-system/
// discuss: https://leetcode.com/problems/design-movie-rental-system/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
// Credit: https://leetcode.com/problems/design-movie-rental-system/solutions/3239007/just-a-runnable-solution/
#[derive(Default)]
struct MovieRentingSystem {
price: std::collections::BTreeMap<(i32, i32), i32>,
unrented: std::collections::HashMap<i32, std::collections::BTreeSet<(i32, i32)>>,
rented: std::collections::BTreeSet<(i32, i32, i32)>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MovieRentingSystem {
fn new(n: i32, entries: Vec<Vec<i32>>) -> Self {
let mut price = std::collections::BTreeMap::new();
let mut unrented =
std::collections::HashMap::<i32, std::collections::BTreeSet<(i32, i32)>>::new();
for e in entries {
let shop = e[0];
let movie = e[1];
let p = e[2];
price.insert((shop, movie), p);
unrented.entry(movie).or_default().insert((p, shop));
}
Self {
price,
unrented,
rented: std::collections::BTreeSet::new(),
}
}
fn search(&mut self, movie: i32) -> Vec<i32> {
let mut ans = Vec::new();
if let Some(s) = self.unrented.get(&movie) {
for (_, shop) in s.iter().take(5) {
ans.push(*shop);
}
}
ans
}
fn rent(&mut self, shop: i32, movie: i32) {
let p = self.price[&(shop, movie)];
self.unrented.get_mut(&movie).unwrap().remove(&(p, shop));
self.rented.insert((p, shop, movie));
}
fn drop(&mut self, shop: i32, movie: i32) {
let p = self.price[&(shop, movie)];
self.rented.remove(&(p, shop, movie));
self.unrented.get_mut(&movie).unwrap().insert((p, shop));
}
fn report(&mut self) -> Vec<Vec<i32>> {
let mut ans = Vec::new();
for (_, shop, movie) in self.rented.iter().take(5) {
ans.push(vec![*shop, *movie]);
}
ans
}
}
/**
* Your MovieRentingSystem object will be instantiated and called as such:
* let obj = MovieRentingSystem::new(n, entries);
* let ret_1: Vec<i32> = obj.search(movie);
* obj.rent(shop, movie);
* obj.drop(shop, movie);
* let ret_4: Vec<Vec<i32>> = obj.report();
*/
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1912_example_1() {
let mut movie_renting_system = MovieRentingSystem::new(
3,
vec![
vec![0, 1, 5],
vec![0, 2, 6],
vec![0, 3, 7],
vec![1, 1, 4],
vec![1, 2, 7],
vec![2, 1, 5],
],
);
assert_eq!(movie_renting_system.search(1), vec![1, 0, 2]); // 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.
movie_renting_system.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3].
movie_renting_system.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1].
assert_eq!(movie_renting_system.report(), vec![vec![0, 1], vec![1, 2]]); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.Z
movie_renting_system.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2].
assert_eq!(movie_renting_system.search(2), vec![0, 1]); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.
}
}
// Accepted solution for LeetCode #1912: Design Movie Rental System
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1912: Design Movie Rental System
// class MovieRentingSystem {
// private Map<Integer, TreeSet<int[]>> available = new HashMap<>();
// private Map<Long, Integer> priceMap = new HashMap<>();
// private TreeSet<int[]> rented = new TreeSet<>((a, b) -> {
// if (a[0] != b[0]) {
// return a[0] - b[0];
// }
// if (a[1] != b[1]) {
// return a[1] - b[1];
// }
// return a[2] - b[2];
// });
//
// public MovieRentingSystem(int n, int[][] entries) {
// for (int[] entry : entries) {
// int shop = entry[0], movie = entry[1], price = entry[2];
// available
// .computeIfAbsent(movie, k -> new TreeSet<>((a, b) -> {
// if (a[0] != b[0]) {
// return a[0] - b[0];
// }
// return a[1] - b[1];
// }))
// .add(new int[] {price, shop});
// priceMap.put(f(shop, movie), price);
// }
// }
//
// public List<Integer> search(int movie) {
// List<Integer> res = new ArrayList<>();
// if (!available.containsKey(movie)) {
// return res;
// }
// int cnt = 0;
// for (int[] item : available.get(movie)) {
// res.add(item[1]);
// if (++cnt == 5) {
// break;
// }
// }
// return res;
// }
//
// public void rent(int shop, int movie) {
// int price = priceMap.get(f(shop, movie));
// available.get(movie).remove(new int[] {price, shop});
// rented.add(new int[] {price, shop, movie});
// }
//
// public void drop(int shop, int movie) {
// int price = priceMap.get(f(shop, movie));
// rented.remove(new int[] {price, shop, movie});
// available.get(movie).add(new int[] {price, shop});
// }
//
// public List<List<Integer>> report() {
// List<List<Integer>> res = new ArrayList<>();
// int cnt = 0;
// for (int[] item : rented) {
// res.add(Arrays.asList(item[1], item[2]));
// if (++cnt == 5) {
// break;
// }
// }
// return res;
// }
//
// private long f(int shop, int movie) {
// return ((long) shop << 30) | movie;
// }
// }
//
// /**
// * Your MovieRentingSystem object will be instantiated and called as such:
// * MovieRentingSystem obj = new MovieRentingSystem(n, entries);
// * List<Integer> param_1 = obj.search(movie);
// * obj.rent(shop,movie);
// * obj.drop(shop,movie);
// * List<List<Integer>> param_4 = obj.report();
// */
Use this to step through a reusable interview workflow for this problem.
Use a simple list or array for storage. Each operation (get, put, remove) requires a linear scan to find the target element — O(n) per operation. Space is O(n) to store the data. The linear search makes this impractical for frequent operations.
Design problems target O(1) amortized per operation by combining data structures (hash map + doubly-linked list for LRU, stack + min-tracking for MinStack). Space is always at least O(n) to store the data. The challenge is achieving constant-time operations through clever structure composition.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.