MediumNo. 1045

Customers Who Bought All Products — LeetCode 1045 Python Solution

Topics
Database
Reading time
2 min

Table schema

SQLTable schema
Table: Customer +-------------+---------+ | Column Name | Type | +-------------+---------+ | customer_id | int | | product_key | int | +-------------+---------+ This table may contain duplicates rows. customer_id is not NULL.

Example

SQLExample
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| customer_id | int     |
| product_key | int     |
+-------------+---------+
This table may contain duplicates rows. 
customer_id is not NULL.
product_key is a foreign key (reference column) to Product table.

Python solution

PythonSolution
import duckdb
import pandas as pd

def solution(customer: pd.DataFrame, product: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Customer", customer)
    con.register("Product", product)
    return con.execute("""SELECT customer_id
FROM Customer
GROUP BY 1
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(1) FROM Product);""").df()

Complexity

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Frequently asked questions

How hard is LeetCode 1045. Customers Who Bought All Products?

LeetCode 1045. Customers Who Bought All Products is rated Medium on LeetCode.

What topics does LeetCode 1045. Customers Who Bought All Products cover?

LeetCode 1045. Customers Who Bought All Products is tagged Database on LeetCode.

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.

Free to download. Check it runs on your machine, then pick a plan.