Sponsored
Sponsored
In this approach, we'll use SQL's GROUP BY
and HAVING
clause to find customers who bought all products. We will count the number of distinct product_keys for each customer_id and compare it to the total number of products.
Time Complexity: O(N * M), where N is the number of customers and M is the number of products due to the join and counting.
Space Complexity: O(K), where K is the number of distinct customer_ids in the result.
1// Since this is more about using SQL, we can't directly implement this in C.
2// Here we showcase how it can be structured logically in SQL.
3char* query = "
4SELECT customer_id
5FROM Customer
6GROUP BY customer_id
7HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
8";
This SQL query groups rows by customer_id
in the Customer
table, then counts distinct product_key
values for each group. The HAVING
clause checks if the count for each customer_id equals the total count of products. Only customer_ids that satisfy this condition appear in the results.
In this approach, we'll manually replicate the SQL logic using hash maps or dictionaries in a programming language. We'll count the distinct products each customer has bought using a hashmap and verify if it matches the total number of products.
Time Complexity: O(N), processes each entry of customer_data.
Space Complexity: O(U), U being the summed size of sets in the dictionary.
1def
customer_id
We use a defaultdict
to track products bought by each customer, forming a set for each customer to store unique products. After forming these sets, we iterate over to check whose product count equals product_count
, the total number of products. Those customer_ids are captured and returned.