#3554

Find Category Recommendation Pairs

Hard
DatabaseHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can use a hash map to group users by category. This allows us to efficiently find common users between category pairs without nested loops.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a map where each category maps to a set of users who purchased products in that category.
  2. 2Step 2: For each category pair, find the intersection of user sets and count unique users.
  3. 3Step 3: Report pairs with at least 3 unique users.
solution.py9 lines
1# Full working Python code
2SELECT category1, category2
3FROM (SELECT c1.category AS category1, c2.category AS category2, COUNT(DISTINCT pp.user_id) AS user_count
4FROM ProductInfo c1
5JOIN ProductPurchases pp ON c1.product_id = pp.product_id
6JOIN ProductInfo c2 ON c1.category < c2.category
7JOIN ProductPurchases pp2 ON c2.product_id = pp2.product_id AND pp.user_id = pp2.user_id
8GROUP BY category1, category2) AS counts
9WHERE user_count >= 3;

Complexity note: The complexity is linear since we only iterate through the data a few times and use hash maps for efficient lookups.

  • 1Utilizing hash maps can significantly reduce time complexity.
  • 2Understanding user-category relationships is crucial for efficient querying.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.