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.
1using System;
2using System.Collections.Generic;
public class Solution {
public static List<int> CustomersWhoBoughtAllProducts(int[][] customerData, int totalProducts) {
Dictionary<int, HashSet<int>> customerMap = new Dictionary<int, HashSet<int>>();
foreach (var data in customerData) {
int customerId = data[0];
int productKey = data[1];
if (!customerMap.ContainsKey(customerId)) {
customerMap[customerId] = new HashSet<int>();
}
customerMap[customerId].Add(productKey);
}
List<int> result = new List<int>();
foreach (var entry in customerMap) {
if (entry.Value.Count == totalProducts) {
result.Add(entry.Key);
}
}
return result;
}
public static void Main() {
int[][] customerData = new int[][] {
new int[] { 1, 5 }, new int[] { 2, 6 }, new int[] { 3, 5 },
new int[] { 3, 6 }, new int[] { 1, 6 }
};
int totalProducts = 2; // Total distinct products
Console.WriteLine(String.Join(", ", CustomersWhoBoughtAllProducts(customerData, totalProducts))); // Outputs: 1, 3
}
}
This solution assembles a Dictionary
where the keys are customer IDs and values are HashSet
of distinct product keys. We loop through all entries in customerData
to create these mappings, then inspect the resulting dictionary for customers whose product set size equals the total number of products.