Talentd
FleetCode
Make and follow sheets.Sign in

Customers Who Bought All Products solution and explanation

MediumDatabase5 min read64.7% acceptanceUpdated 9 Apr 2026
Customers Who Bought All Products | Leetcode 1045 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 5:26 · 9K viewsWatch on YouTube
9 more videos on this problem
  1. Customers Who Bought All Products | Leetcode 1045 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 5:26 · 9K views
  2. 127. Databricks | Pyspark| SQL Coding Interview:LeetCode-1045: Customers Who Bought All ProductsRaja's Data Engineering · 9:51 · 5K views
  3. LeetCode Medium 1045 Amazon Interview SQL Question with Detailed ExplanationEveryday Data Science · 7:01 · 5K views
  4. LeetCode 1045: Customers Who Bought All Products [SQL]Frederik Müller · 9:40 · 1K views
  5. 1045. Customers Who Bought All Products - LeetCode SQL Solution [MySQL]Code with Carter · 2:42 · 1K views
  6. Customers Who Bought All Products - Leetcode 1045 | Week 4 | Qs 15The Big Data Show · 3:08 · 822 views
  7. LeetCode - 1045. Customers Who Bought All Products (SQL)Chain Of Thought · 5:08 · 134 views
  8. Mastering SQL Aggregations: Find Customers Who Bought ALL Products - Leetcode - 1045vanAmsen · 3:52 · 117 views
  9. 1045. Customers Who Bought All Products | sql 50 | LeetCode | Easy ExplainationSheCodes · 4:36 · 66 views
  10. Leetcode SQL 50 | 1045. Customers Who Bought All Products SolutionTrang Ng · 4:01 · 61 views

The problem

Table: Customer

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| customer_id | int     |
| product_key | int     |
+-------------+---------+
This table may contain duplicates rows. 
customer_id is not NULL.
product_key is a foreign key (reference column) to Product table.

Table: Product

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_key | int     |
+-------------+---------+
product_key is the primary key (column with unique values) for this table.

Write a solution to report the customer ids from the Customer table that bought all the products in the Product table.

Return the result table in any order.

The result format is in the following example.

Example 1:

Input: 
Customer table:
+-------------+-------------+
| customer_id | product_key |
+-------------+-------------+
| 1           | 5           |
| 2           | 6           |
| 3           | 5           |
| 3           | 6           |
| 1           | 6           |
+-------------+-------------+
Product table:
+-------------+
| product_key |
+-------------+
| 5           |
| 6           |
+-------------+
Output: 
+-------------+
| customer_id |
+-------------+
| 1           |
| 3           |
+-------------+
Explanation: 
The customers who bought all the products (5 and 6) are customers with IDs 1 and 3.

Approach overview

Problem Overview: You are given a purchase table that records which customer bought which product. The goal is to return all customers who have purchased every product that exists in the Products table. A valid customer must have bought each product at least once.

Approach 1: SQL GROUP BY with COUNT(DISTINCT) (O(n log n) time, O(n) space)

This is the standard relational database solution. First determine the total number of products using COUNT(*) on the Product table. Then group the Customer purchase records by customer_id and count how many distinct products each customer bought. If that count matches the total number of products, the customer purchased the full catalog. SQL engines internally use grouping and sorting or hashing, which leads to roughly O(n log n) processing depending on indexing. This approach is concise, declarative, and preferred when solving problems tagged under Database or SQL.

Approach 2: HashMap / Dictionary Counting (O(n) time, O(n) space)

If you implement the logic in a programming language instead of pure SQL, track purchases using a hash map. First compute the number of unique products from the product list. Then iterate through the purchase records and store products bought by each customer inside a hash set or dictionary entry. After processing all records, check which customers have a product set size equal to the total product count. Hash lookups and insertions run in constant time, so the overall complexity is O(n) for n purchase rows. This approach mirrors typical interview-style reasoning using hash tables or dictionaries.

Key Insight: The problem reduces to comparing two counts: the total number of products in the system and the number of unique products purchased by each customer. As soon as those values match, the customer qualifies.

Recommended for interviews: Interviewers usually expect the counting insight first. Explaining the hash set or dictionary method demonstrates algorithmic thinking and clean O(n) reasoning. For database-focused interviews, the GROUP BY + HAVING COUNT(DISTINCT ...) solution is the canonical answer and shows strong SQL fundamentals.

Approach 1: Approach using SQL with Group By

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.

# For illustrative purposes as Python would need a cursor from a DB connection
query = """
SELECT customer_id
FROM Customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
"""
// Not directly executable Java, but SQL logic can be prepared in Java context like this
String query = "
SELECT customer_id
FROM Customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
";
// C++ doesn't natively handle SQL, so this pseudocode outlines the logic.
std::string query = "
SELECT customer_id
FROM Customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
";
// JavaScript would rely on SQL directly accessed through a client or like node-sql
const query = `
SELECT customer_id
FROM Customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
`;
// Since this is more about using SQL, we can't directly implement this in C.
// Here we showcase how it can be structured logically in SQL.
char* query = "
SELECT customer_id
FROM Customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
";
// Not directly executable in C#, but encapsulating SQL syntax for database access
string query = "
SELECT customer_id
FROM Customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
";

This SQL used within Python would leverage PEP-249-compliant DB API or ORM. It's a direct translation to highlight SQL-centric solution paths for dataset manipulation.

Complexity

Time Complexity: O(N * M), looping and count mechanism.
Space Complexity: O(K), where K is number of query results.

Try this approach in the editor

Approach 2: Approach Using Programming Language with Hashmap/Dictionary

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.

def customers_who_bought_all_products(customer_data, product_count):
    from collections import defaultdict
    customer_products = defaultdict(set)

    for customer_id, product_key in customer_data:
        customer_products[customer_id].add(product_key)

    all_product_customers = [
        customer_id
        for customer_id, products in customer_products.items()
        if len(products) == product_count
    ]

    return all_product_customers

# Example execution
customer_data = [(1, 5), (2, 6), (3, 5), (3, 6), (1, 6)]
product_count = 2  # Total distinct products
print(customers_who_bought_all_products(customer_data, product_count))  # Outputs: [1, 3]
import java.util.*;

public class Solution {
    public static List<Integer> customersWhoBoughtAllProducts(int[][] customerData, int totalProducts) {
        Map<Integer, Set<Integer>> customerMap = new HashMap<>();

        for (int[] data : customerData) {
            int customerId = data[0];
            int productKey = data[1];
            customerMap.computeIfAbsent(customerId, k -> new HashSet<>()).add(productKey);
        }

        List<Integer> result = new ArrayList<>();
        for (Map.Entry<Integer, Set<Integer>> entry : customerMap.entrySet()) {
            if (entry.getValue().size() == totalProducts) {
                result.add(entry.getKey());
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] customerData = {{1, 5}, {2, 6}, {3, 5}, {3, 6}, {1, 6}};
        int totalProducts = 2;  // Total distinct products
        System.out.println(customersWhoBoughtAllProducts(customerData, totalProducts));  // Outputs: [1, 3]
    }
}
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <vector>

std::vector<int> customersWhoBoughtAllProducts(const std::vector<std::pair<int, int>>& customerData, int totalProducts) {
    std::unordered_map<int, std::unordered_set<int>> customerMap;

    for (const auto& [customerId, productKey] : customerData) {
        customerMap[customerId].insert(productKey);
    }

    std::vector<int> result;
    for (const auto& [customerId, products] : customerMap) {
        if (products.size() == totalProducts) {
            result.push_back(customerId);
        }
    }

    return result;
}

int main() {
    std::vector<std::pair<int, int>> customerData = { {1, 5}, {2, 6}, {3, 5}, {3, 6}, {1, 6} };
    int totalProducts = 2;  // Total distinct products
    std::vector<int> result = customersWhoBoughtAllProducts(customerData, totalProducts);
    for (int id : result) {
        std::cout << id << " ";  // Outputs: 1 3
    }
    return 0;
}
function customersWhoBoughtAllProducts(customerData, totalProducts) {
    const customerMap = new Map();

    customerData.forEach(([customerId, productKey]) => {
        if (!customerMap.has(customerId)) {
            customerMap.set(customerId, new Set());
        }
        customerMap.get(customerId).add(productKey);
    });

    return [...customerMap.entries()].filter(
        ([, productSet]) => productSet.size === totalProducts
    ).map(([customerId, ]) => customerId);
}

// Example execution
const customerData = [[1, 5], [2, 6], [3, 5], [3, 6], [1, 6]];
const totalProducts = 2;  // Total distinct products
console.log(customersWhoBoughtAllProducts(customerData, totalProducts));  // Outputs: [1, 3]
using System;
using 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
    }
}

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.

Complexity

Time Complexity: O(N), processes each entry of customer_data.
Space Complexity: O(U), U being the summed size of sets in the dictionary.

Try this approach in the editor

Approach 3: Grouping and Subquery

We can group the Customer table by customer_id, and then use the HAVING clause to filter out the customers who have not purchased all products. To do this, we can use a subquery to find the total number of distinct products, and then compare it with the number of distinct products purchased by each customer.

# Write your MySQL query statement below
SELECT customer_id
FROM Customer
GROUP BY 1
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(1) FROM Product);
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach using SQL with Group By

Time Complexity: O(N * M), looping and count mechanism.
Space Complexity: O(K), where K is number of query results.

Approach Using Programming Language with Hashmap/Dictionary

Time Complexity: O(N), processes each entry of customer_data.
Space Complexity: O(U), U being the summed size of sets in the dictionary.

Grouping and Subquery–

Complexity analysis

ApproachTimeSpaceWhen to Use
SQL GROUP BY + COUNT(DISTINCT)O(n log n)O(n)Best for database queries or SQL interviews where aggregation is expected
HashMap / Dictionary with SetsO(n)O(n)General programming solution when solving outside SQL using Python, Java, or JavaScript

Frequently asked questions

Is Customers Who Bought All Products easy or hard?

Customers Who Bought All Products is rated Medium on LeetCode with about a 62% acceptance rate. The difficulty comes from recognizing the aggregation pattern: compare each customer's distinct product count with the total number of products.

Customers Who Bought All Products Python/Java solution

In Python, use a dictionary mapping each customer to a set of product IDs and compare the set size with the total number of products. In Java, use HashMap<Integer, HashSet<Integer>> to track purchases and filter customers whose set size equals the total catalog size.

How to solve Customers Who Bought All Products in O(n)?

Use a hashmap where each customer maps to a set of purchased products. First compute the total number of products. Then iterate through purchase records and insert product IDs into each customer's set. After processing all rows, return customers whose set size equals the total product count, giving O(n) time complexity.

What is the best approach for Customers Who Bought All Products?

The most common solution uses SQL GROUP BY with COUNT(DISTINCT product_id). Count the total number of products, then group purchase records by customer and keep only those where the distinct product count matches the total. This directly expresses the requirement and runs in about O(n log n) depending on the database engine.

Is Customers Who Bought All Products asked at Google/Amazon/Meta?

Problems that involve SQL aggregation, GROUP BY, and filtering with HAVING appear frequently in database interviews at companies like Amazon, Meta, and Google. Variations often test whether you can compare grouped counts against global totals.

What data structure is used in Customers Who Bought All Products?

The programming approach relies on a hash map combined with a hash set. The hash map stores customers as keys, and each value tracks the set of products they purchased. This structure allows constant-time insertion and membership checks.

What is the time complexity of Customers Who Bought All Products?

The SQL aggregation solution typically runs in O(n log n) time because grouping may require sorting or hashing internally. A programming implementation using hash maps and sets can achieve O(n) time by processing each purchase row once and performing constant-time hash operations.

Comments

Now write it yourselfClose this page and solve Customers Who Bought All Products in the editor, without looking.
Practise Customers Who Bought All Products