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 in C#, but encapsulating SQL syntax for database access
2string query = "
3SELECT customer_id
4FROM Customer
5GROUP BY customer_id
6HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
7";
This query compiled into SQL and executed through ADO.NET or Entity Framework with connection object for SQL Server, MYSQL, etc., yielding customer_ids satisfying condition.
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.