#3521

Find Product Recommendation Pairs

Medium
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)

Utilize a hash map to count co-purchases efficiently, reducing redundant checks and improving performance.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a hash map to store product pairs and their customer counts.
  2. 2Step 2: For each user, retrieve their purchased products and generate pairs, updating the hash map.
  3. 3Step 3: Filter the hash map for pairs with at least 3 customers.
solution.py7 lines
1# Full working Python code
2SELECT product1_id, product2_id, customer_count
3FROM (SELECT pp1.product_id AS product1_id, pp2.product_id AS product2_id, COUNT(DISTINCT pp.user_id) AS customer_count
4FROM ProductPurchases pp
5JOIN ProductPurchases pp2 ON pp.user_id = pp2.user_id AND pp.product_id < pp2.product_id
6GROUP BY pp1.product_id, pp2.product_id) AS pairs
7WHERE customer_count >= 3;

Complexity note: This approach efficiently counts pairs using a hash map, reducing the need for nested loops.

  • 1Co-purchase patterns reveal user behavior.
  • 2Using hash maps optimizes counting pairs.

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