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// Not directly executable Java, but SQL logic can be prepared in Java context like this
2String query = "
3SELECT customer_id
4FROM Customer
5GROUP BY customer_id
6HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
7";
Java would execute this SQL via database connection objects. This code is more a template to prepare and submit to the DBMS.
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.