Unpopular Books — LeetCode 1098 Python Solution

MediumLeetCode PremiumDatabase
Problem
#1098
Reading time
3 min

Table schema

SQL
Table: Books +----------------+---------+ | Column Name | Type | +----------------+---------+ | book_id | int | | name | varchar | | available_from | date | +----------------+---------+ book_id is the primary key (column with unique values) of this table. Table: Orders +----------------+---------+ | Column Name | Type | +----------------+---------+ | order_id | int | | book_id | int | | quantity | int | | dispatch_date | date | +----------------+---------+ order_id is the primary key (column with unique values) of this table.

Example

SQL
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| book_id        | int     |
| name           | varchar |
| available_from | date    |
+----------------+---------+
book_id is the primary key (column with unique values) of this table.

Python solution

Python
import duckdb
import pandas as pd

def solution(books: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Books", books)
    con.register("Orders", orders)
    return con.execute("""SELECT book_id, name
FROM
    Books
    LEFT JOIN Orders USING (book_id)
WHERE available_from < '2019-05-23'
GROUP BY 1
HAVING SUM(IF(dispatch_date >= '2018-06-23', quantity, 0)) < 10;""").df()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1098. Unpopular Books?
LeetCode 1098. Unpopular Books is rated Medium on LeetCode.
What topics does LeetCode 1098. Unpopular Books cover?
LeetCode 1098. Unpopular Books is tagged Database on LeetCode.
Is LeetCode 1098. Unpopular Books a premium problem?
Yes. LeetCode 1098. Unpopular Books is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview