Similar Problems

Similar Problems not available

Movie Rating - Leetcode Solution

Companies:

LeetCode:  Movie Rating Leetcode Solution

Difficulty: Medium

Topics: database  

Problem Statement:

You are given a list of movie ratings. You need to implement a method, MovieRating, to calculate the average rating of all the movies with a given rating.

The method should take in two parameters:

ratings - a list of integers where each integer represents the rating of a movie. The rating of each movie will be an integer between 1 and 5, inclusive.

ratingToCount - an integer representing the rating for which the average rating needs to be calculated.

The method should return a float that represents the average rating of all the movies with the given rating.

Note:

The list ratings may be empty.

The ratingToCount will always be an integer between 1 and 5, inclusive.

If there are no movies with the given rating, the method should return 0.

Solution:

The problem can be solved using a simple mathematical formula that calculates the average of a list of numbers.

First, we need to count the number of movies in the list that have the given rating. We can do this by looping through the list and counting how many times the given rating appears.

Next, we need to calculate the sum of the ratings of all the movies that have the given rating. We can do this by looping through the list again and adding up the ratings of all the movies with the given rating.

Finally, we need to divide the sum of the ratings by the count of movies to get the average rating. This can be done using the formula:

average rating = sum of ratings / count of movies

Below is the Python implementation of the solution:

class Solution:
    def MovieRating(self, ratings: List[int], ratingToCount: int) -> float:

        # count the number of movies with the given rating
        count = 0
        for rating in ratings:
            if rating == ratingToCount:
                count += 1

        # if there are no movies with the given rating, return 0
        if count == 0:
            return 0

        # calculate the sum of the ratings of all the movies with the given rating
        sum_ratings = 0
        for rating in ratings:
            if rating == ratingToCount:
                sum_ratings += rating

        # calculate the average rating
        average_rating = sum_ratings / count

        return average_rating

Time Complexity:

The time complexity of the solution is O(N), where N is the number of movies in the list.

Space Complexity:

The space complexity of the solution is O(1), as we are not using any extra space.

Movie Rating Solution Code

1