LeetCode 1398: Customers Who Bought Products A and B but Not C Solution

Master LeetCode problem 1398 (Customers Who Bought Products A and B but Not C), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1398. Customers Who Bought Products A and B but Not C

Medium

Problem Explanation

Explanation:

To solve this problem, we can iterate through the given list of transactions and keep track of customers who bought products A and B but not C. We can use a hashmap to store the count of each product bought by each customer. Then, we can iterate through the hashmap to identify customers who bought products A and B but not C.

  • Create a hashmap to store the count of each product bought by each customer.
  • Iterate through the transactions list to populate the hashmap.
  • Iterate through the hashmap to identify customers who bought products A and B but not C.
  • Return the list of customer IDs who satisfy the condition.

Time Complexity: O(N), where N is the number of transactions. Space Complexity: O(N), where N is the number of transactions.

:

Solution Code

import java.util.*;

class Solution {
    public List<Integer> peopleBoughtProducts(List<List<String>> products) {
        Map<Integer, Map<String, Integer>> customers = new HashMap<>();
        Set<Integer> result = new HashSet<>();
        
        for (List<String> product : products) {
            int id = Integer.parseInt(product.get(0));
            String item = product.get(1);
            
            if (!customers.containsKey(id)) {
                customers.put(id, new HashMap<>());
            }
            customers.get(id).put(item, customers.get(id).getOrDefault(item, 0) + 1);
            
            if (customers.get(id).containsKey("A") && customers.get(id).containsKey("B") && !customers.get(id).containsKey("C")) {
                result.add(id);
            }
        }
        
        return new ArrayList<>(result);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1398 (Customers Who Bought Products A and B but Not C)?

This page provides optimized solutions for LeetCode problem 1398 (Customers Who Bought Products A and B but Not C) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1398 (Customers Who Bought Products A and B but Not C)?

The time complexity for LeetCode 1398 (Customers Who Bought Products A and B but Not C) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1398 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1398 in Java, C++, or Python.

Back to LeetCode Solutions