Customers Who Bought All Products — LeetCode 1045 Python Solution

MediumDatabase
Problem
#1045
Reading time
2 min

Table schema

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

Example

SQL
+-------------+---------+
| 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

Python
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

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

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.

Get Stealth Interview