LeetCode solutions

3891. Find Category Recommendation Pairs

My accepted SQL solution to LeetCode problem 3891, Find Category Recommendation Pairs, running in 675ms.

  • Difficulty: Hard
  • SQL
  • Runtime 675ms
  • Memory 0.0B

Read the problem on LeetCode View on GitHub

SQL

Accepted on LeetCode — runtime 675ms, memory 0.0B, accepted 2026-01-02.

sql
SELECT 
    uc1.category AS category1,
        uc2.category AS category2,
            COUNT(DISTINCT uc1.user_id) AS customer_count
            FROM (
                SELECT DISTINCT pp.user_id, pi.category
                    FROM ProductPurchases pp
                        JOIN ProductInfo pi ON pp.product_id = pi.product_id
                        ) uc1
                        JOIN (
                            SELECT DISTINCT pp.user_id, pi.category
                                FROM ProductPurchases pp
                                    JOIN ProductInfo pi ON pp.product_id = pi.product_id
                                    ) uc2 
                                        ON uc1.user_id = uc2.user_id 
                                            AND uc1.category < uc2.category
                                            GROUP BY uc1.category, uc2.category
                                            HAVING COUNT(DISTINCT uc1.user_id) >= 3
                                            ORDER BY customer_count DESC, category1, category2

Source