Not Boring Movies solution and explanation
9 more videos on this problem
Not Boring Movies | Leetcode 620 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 4:32 · 10K views
LeetCode 620: Not Boring Movies [SQL]Frederik Müller · 6:07 · 4K views
[MySQL] Leetcode 620. Not Boring Movies [SQL #2]Eric Programming · 3:52 · 1K views
LeetCode 620 - Not Boring Movies (Python and SQL) [Easy]Ryan & Matt Data Science · 5:08 · 368 views
LeetCode 620 - Not Boring Movies | SQL Interview QuestionBig Tech Mindset · 3:04 · 329 views
Solving LeetCode Problem 620 - Not Boring Movies Using SQLvanAmsen · 4:26 · 120 views
620. Not Boring Movies | LeetCode | SQL | Solution | Interview ProblemData Alchemist · 4:14 · 108 views
15. Leetcode 620. Not Boring Movies : MYSQLWeb Fusion with Bharadwaj · 7:56 · 101 views
620. Not Boring Movies || MYSQL || LEETCODE SQL #3Nitin Pal · 5:55 · 98 views
620. Not Boring Movies (Leetcode Easy)Programming Live with Larry · 1:38 · 63 views
The problem
Table: Cinema
+----------------+----------+ | Column Name | Type | +----------------+----------+ | id | int | | movie | varchar | | description | varchar | | rating | float | +----------------+----------+ id is the primary key (column with unique values) for this table. Each row contains information about the name of a movie, its genre, and its rating. rating is a 2 decimal places float in the range [0, 10]
Write a solution to report the movies with an odd-numbered ID and a description that is not "boring".
Return the result table ordered by rating in descending order.
The result format is in the following example.
Example 1:
Input: Cinema table: +----+------------+-------------+--------+ | id | movie | description | rating | +----+------------+-------------+--------+ | 1 | War | great 3D | 8.9 | | 2 | Science | fiction | 8.5 | | 3 | irish | boring | 6.2 | | 4 | Ice song | Fantacy | 8.6 | | 5 | House card | Interesting | 9.1 | +----+------------+-------------+--------+ Output: +----+------------+-------------+--------+ | id | movie | description | rating | +----+------------+-------------+--------+ | 5 | House card | Interesting | 9.1 | | 1 | War | great 3D | 8.9 | +----+------------+-------------+--------+ Explanation: We have three movies with odd-numbered IDs: 1, 3, and 5. The movie with ID = 3 is boring so we do not include it in the answer.
Approach overview
Problem Overview: The cinema table contains movie records with id, movie, description, and rating. Return only movies whose id is odd and whose description is not 'boring'. The result must be sorted by rating in descending order.
Approach 1: SQL Query Using Simple Filtering (O(n log n) time, O(1) extra space)
This is the direct database solution. Filter rows with two conditions: id % 2 = 1 (odd IDs) and description != 'boring'. After filtering, apply ORDER BY rating DESC to sort the result. The database scans rows and performs a sort, giving roughly O(n log n) time due to ordering. This approach relies on standard SQL filtering and works cleanly in ORMs such as SQLAlchemy.
Approach 2: Query Using SQL Conditions (Entity Framework) (O(n log n) time, O(1) extra space)
ORM frameworks like Entity Framework translate high‑level conditions into SQL. You express the same logic using conditional filters: select rows where id % 2 != 0 and description != "boring", then order by rating descending. The ORM generates the SQL query and pushes computation to the database engine. Complexity remains O(n log n) due to sorting, while the query benefits from database indexes if present.
Approach 3: Divide and Conquer (O(n log n) time, O(n) space)
If the dataset is loaded into memory (for example in a service layer), you can split the list of movies into halves, filter each half recursively for valid rows, and merge the results. During the merge step, apply a descending sort by rating similar to merge sort. The divide‑and‑conquer structure keeps filtering independent per segment, and the final merge step maintains ordering. This resembles techniques used in divide and conquer algorithms.
Approach 4: Dynamic Programming (Tabulation) (O(n log n) time, O(n) space)
A tabulation approach processes rows sequentially and stores valid results in a table or list. For each movie, check two conditions: odd ID and non‑boring description. Valid rows are appended to the DP table, which represents the accumulated filtered set. After processing all rows, sort the stored entries by rating in descending order. While DP is unnecessary for this problem, the pattern demonstrates incremental filtering and aggregation often used in dynamic programming workflows.
Recommended for interviews: The straightforward SQL filtering approach is what interviewers expect. It shows you understand conditional selection (WHERE) and result ordering (ORDER BY). Alternative approaches like divide‑and‑conquer or DP demonstrate algorithmic thinking when data is handled outside the database, but the optimal production solution keeps filtering inside the SQL query.
Approach 1: SQL Query Using Simple Filtering
This approach involves using a straightforward SQL query to filter movies based on conditions specified in the question. We will look for movies with an ID that is odd and where the description is not 'boring'. Once filtered, results will be sorted according to the ratings in descending order.
from sqlalchemy import create_engine, Table, Column, Integer, String, Float, MetaData
from sqlalchemy.orm import sessionmaker
# Create an in-memory SQLite database
engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData(bind=engine)
# Define the Cinema table
cinema_table = Table('Cinema', metadata,
Column('id', Integer, primary_key=True),
Column('movie', String),
Column('description', String),
Column('rating', Float))
# Create the table
metadata.create_all()
# Insert example data
engine.execute(cinema_table.insert(), [
{'id': 1, 'movie': 'War', 'description': 'great 3D', 'rating': 8.9},
{'id': 2, 'movie': 'Science', 'description': 'fiction', 'rating': 8.5},
{'id': 3, 'movie': 'irish', 'description': 'boring', 'rating': 6.2},
{'id': 4, 'movie': 'Ice song', 'description': 'Fantasy', 'rating': 8.6},
{'id': 5, 'movie': 'House card', 'description': 'Interesting', 'rating': 9.1}
])
# Query for not boring movies with odd IDs
Session = sessionmaker(bind=engine)
session = Session()
query = session.query(cinema_table).filter(
sql.text('id % 2 != 0 AND description != "boring"')
).order_by(sql.text('rating DESC'))
results = query.all()
for row in results:
print(f'id: {row.id}, movie: {row.movie}, description: {row.description}, rating: {row.rating}')We use SQLAlchemy to define a table 'Cinema' and insert the sample data. We query this table using conditions specified: id as odd and a non-'boring' description, finally ordering by ratings in descending order. The results are printed one by one.
The time complexity of this approach is O(n log n) due to sorting of the movies after filtering, and space complexity is O(1) as we do not use extra space apart from input size.
Approach 2: Query Using SQL Conditions
This approach directly uses SQL logic to filter out the records based on conditions specified in the question: selecting only those entries with an odd-numbered ID and a non-boring description, followed by sorting the result set based on ratings in descending order.
using System;
using System.Linq;
using System.Collections.Generic;
public class Movie {
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public float Rating { get; set; }
}
public class Program {
public static void Main() {
var movies = new List<Movie> {
new Movie { Id = 1, Name = "War", Description = "great 3D", Rating = 8.9f },
new Movie { Id = 2, Name = "Science", Description = "fiction", Rating = 8.5f },
new Movie { Id = 3, Name = "irish", Description = "boring", Rating = 6.2f },
new Movie { Id = 4, Name = "Ice song", Description = "Fantasy", Rating = 8.6f },
new Movie { Id = 5, Name = "House card", Description = "Interesting", Rating = 9.1f }
};
var result = movies
.Where(m => m.Id % 2 != 0 && m.Description != "boring")
.OrderByDescending(m => m.Rating);
foreach (var movie in result) {
Console.WriteLine($"Id: {movie.Id}, Movie: {movie.Name}, Description: {movie.Description}, Rating: {movie.Rating}");
}
}
}We begin by defining a Movie class and a list of Movie objects, after which we filter through this list in a LINQ query to fetch movies with odd-numbered IDs while excluding descriptions marked 'boring'. Finally, results are ordered by rating before being printed.
The time complexity of this approach is O(n log n) due to sorting, and the space complexity is O(n) because we store the list of filtered movies.
Approach 3: Divide and Conquer
This approach involves breaking down the problem into smaller sub-problems, solving each one individually, and then combining their solutions to solve the original problem. This is a powerful technique used in algorithms like Merge Sort and Quick Sort. It allows us to efficiently tackle the problem by utilizing recursive problem-solving.
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
arr = [12, 11, 13, 5, 6, 7]
print("Given array:", arr)
merge_sort(arr)
print("Sorted array:", arr)#include <stdio.h>
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr) / sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("Sorted array is \n");
printArray(arr, arr_size);
return 0;
}This Python implementation of Merge Sort divides the input list recursively and sorts each half. The helper function 'merge_sort' implements recursive division and merging. This is an efficient sort that guarantees O(n log n) performance.
Time Complexity: O(n log n)
Space Complexity: O(n)
Approach 4: Dynamic Programming (Tabulation)
Dynamic programming is a technique used for solving complex problems by breaking them down into simpler subproblems. Tabulation involves solving the subproblems and storing their results in a table (usually an array) to avoid redundant calculations. This approach is efficient for problems where overlapping subproblems and optimal substructure properties exist.
public class FiboTabulation {
public static int fibonacci(int n) {
if (n <= 1) return n;
int[] fib = new int[n + 1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
public static void main(String[] args) {
System.out.println(fibonacci(9)); // Output: 34
}
}function fibonacci(n) {
let fib = Array(n + 1).fill(0);
fib[1] = 1;
for (let i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
console.log(fibonacci(9)); // Output: 34This Java program calculates the nth Fibonacci number using tabulation. An array is used to store the Fibonacci numbers up to n. This approach avoids recursion and computes the result efficiently.
Time Complexity: O(n)
Space Complexity: O(n)
Approach 5: Conditional Filtering + Sorting
We can use the WHERE clause to filter out the records where description is not boring and id is odd, and then use the ORDER BY clause to sort the result in descending order by rating.
# Write your MySQL query statement below
SELECT *
FROM Cinema
WHERE description != 'boring' AND id & 1 = 1
ORDER BY 4 DESC;Complexity comparison
| Approach | Complexity |
|---|---|
| SQL Query Using Simple Filtering | The time complexity of this approach is O(n log n) due to sorting of the movies after filtering, and space complexity is O(1) as we do not use extra space apart from input size. |
| Query Using SQL Conditions | The time complexity of this approach is O(n log n) due to sorting, and the space complexity is O(n) because we store the list of filtered movies. |
| Divide and Conquer | Time Complexity: O(n log n) |
| Dynamic Programming (Tabulation) | Time Complexity: O(n) |
| Conditional Filtering + Sorting | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| SQL Query Using Simple Filtering | O(n log n) | O(1) | Best approach when querying directly from a database using SQL |
| Query Using SQL Conditions (ORM) | O(n log n) | O(1) | When using frameworks like Entity Framework or SQLAlchemy |
| Divide and Conquer | O(n log n) | O(n) | When the dataset is processed in memory and parallel filtering is desired |
| Dynamic Programming (Tabulation) | O(n log n) | O(n) | When building filtered results incrementally before final sorting |
Frequently asked questions
Is Not Boring Movies easy or hard?
Not Boring Movies is classified as Easy. The task only requires understanding SQL WHERE filters, modulus checks for odd IDs, and ORDER BY sorting. It is often used to test basic SQL query writing skills.
Not Boring Movies Python/Java solution
In Python, frameworks like SQLAlchemy express the solution using filters on id and description followed by ordering by rating descending. In Java or C#, ORMs such as Entity Framework generate equivalent SQL queries with the same conditions and sorting logic.
How to solve Not Boring Movies in O(n)?
Pure O(n) is possible only if the database already stores rows indexed or pre‑sorted by rating. Otherwise sorting dominates the complexity. The standard solution scans rows with WHERE conditions and then sorts by rating, giving O(n log n) time in typical implementations.
What is the best approach for Not Boring Movies?
The best approach is a simple SQL query with filtering and sorting. Use WHERE conditions to keep rows where id is odd (id % 2 = 1) and description is not 'boring', then apply ORDER BY rating DESC. This pushes all work to the database engine and runs in roughly O(n log n) time due to sorting.
Is Not Boring Movies asked at Google/Amazon/Meta?
Not Boring Movies is a common introductory SQL filtering problem similar to questions used in database screening rounds. Variants of conditional filtering and ordering appear in interviews at large tech companies including Amazon and Google when testing SQL fundamentals.
What data structure is used in Not Boring Movies?
The problem operates on a relational database table. Conceptually it works on rows in a table structure where filtering conditions select valid records and a sorting operation orders them by rating.
What is the time complexity of Not Boring Movies?
The query typically runs in O(n log n) time because the database must sort the filtered rows by rating. The filtering step itself is O(n). Extra space is O(1) from the query perspective since the database engine manages intermediate memory internally.
