#1341

Movie Rating

Medium
DatabaseHash MapAggregation Functions
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

In the optimal approach, we will use hash maps to efficiently count ratings and calculate averages in a single pass through the data. This reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a hash map to count the number of ratings for each user.
  2. 2Step 2: Use another hash map to accumulate ratings and count for each movie rated in February 2020.
  3. 3Step 3: Determine the user with the maximum ratings count and resolve ties lexicographically.
  4. 4Step 4: Calculate the average rating for each movie and find the one with the highest average, resolving ties lexicographically.
solution.py13 lines
1WITH UserCount AS (
2    SELECT user_id, COUNT(movie_id) AS rating_count
3    FROM MovieRating
4    GROUP BY user_id
5),
6MovieAverage AS (
7    SELECT movie_id, AVG(rating) AS avg_rating, COUNT(rating) AS rating_count
8    FROM MovieRating
9    WHERE created_at BETWEEN '2020-02-01' AND '2020-02-29'
10    GROUP BY movie_id
11)
12SELECT (SELECT name FROM Users u JOIN UserCount uc ON u.user_id = uc.user_id ORDER BY uc.rating_count DESC, u.name ASC LIMIT 1) AS user_name,
13       (SELECT title FROM Movies m JOIN MovieAverage ma ON m.movie_id = ma.movie_id ORDER BY ma.avg_rating DESC, m.title ASC LIMIT 1) AS movie_name;

Complexity note: The time complexity is O(n) because we traverse the MovieRating table a limited number of times, and space complexity is O(n) due to the hash maps storing user counts and movie averages.

  • 1Using hash maps can significantly reduce time complexity.
  • 2Understanding how to group and aggregate data is crucial for SQL queries.

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