#1045
Customers Who Bought All Products
MediumDatabaseHash MapAggregation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a hash map to count purchases per customer and compares it to the total number of products. This reduces the number of checks needed.
⚙️
Algorithm
4 steps- 1Step 1: Count the total number of unique products from the Product table.
- 2Step 2: Create a hash map to count how many unique products each customer has purchased.
- 3Step 3: Iterate through the Customer table, updating the hash map with product counts for each customer.
- 4Step 4: Select customers from the hash map whose count matches the total number of unique products.
solution.py8 lines
1# Full working Python code
2WITH ProductCount AS (SELECT COUNT(*) AS total_products FROM Product),
3CustomerProducts AS (SELECT customer_id, COUNT(DISTINCT product_key) AS product_count
4FROM Customer
5GROUP BY customer_id)
6SELECT customer_id
7FROM CustomerProducts
8WHERE product_count = (SELECT total_products FROM ProductCount);ℹ
Complexity note: The complexity is O(n) because we only need to iterate through the Customer table and the Product table once each.
- 1Understanding how to aggregate data using GROUP BY is crucial.
- 2Using hash maps can significantly optimize counting problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.