Page Recommendations II - Problem
You're building a smart page recommendation system for a social media platform! Your mission is to help users discover new content by leveraging their social connections.
Given two tables:
- Friendship - stores bidirectional friendships between users
- Likes - tracks which users like which pages
Your system should recommend a page to a user if:
- At least one of their friends likes the page
- The user doesn't already like the page themselves
For each valid recommendation, return the user_id, page_id, and friends_likes (how many friends like that page).
Example: If Alice is friends with Bob and Charlie, and both Bob and Charlie like "Tech News" page, but Alice doesn't, then recommend "Tech News" to Alice with friends_likes = 2.
Input & Output
example_1.sql โ Basic Recommendations
$
Input:
Friendship: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\nLikes: [[1,21],[1,22],[2,21],[3,21],[4,22]]
โบ
Output:
[[1,null],[2,22],[3,22],[4,21]]
๐ก Note:
User 1 has no recommendations (already likes pages 21,22). User 2 gets page 22 (friend 1 likes it). User 3 gets page 22 (friend 1 likes it). User 4 gets page 21 (friends 2,3 like it, so friends_likes=2).
example_2.sql โ Multiple Friend Likes
$
Input:
Friendship: [[1,2],[1,3]]\nLikes: [[1,22],[2,21],[2,22],[3,21]]
โบ
Output:
[[1,21],[2,null],[3,22]]
๐ก Note:
User 1 gets page 21 (friends 2,3 both like it, friends_likes=2). User 2 has no new recommendations. User 3 gets page 22 (friend 2 likes it).
example_3.sql โ No Friendships
$
Input:
Friendship: []\nLikes: [[1,21],[2,22],[3,21]]
โบ
Output:
[]
๐ก Note:
No friendships exist, so no recommendations can be made.
Visualization
Tap to expand
Understanding the Visualization
1
Map All Friendships
Create a complete bidirectional friendship graph using UNION ALL
2
Connect Friends to Likes
JOIN friendships with likes to see what friends enjoy
3
Exclude Existing Preferences
LEFT JOIN with user's own likes and filter NULL to find new recommendations
4
Count and Recommend
GROUP BY to count how many friends like each recommended page
Key Takeaway
๐ฏ Key Insight: Use SQL JOINs strategically - bidirectional CTE for friendships, LEFT JOIN exclusion for filtering, and GROUP BY for counting friend recommendations efficiently.
Time & Space Complexity
Time Complexity
O(n log n)
Efficient JOINs with proper indexing on user_id and page_id columns
โก Linearithmic
Space Complexity
O(n)
Temporary space for JOIN operations and result aggregation
โก Linearithmic Space
Constraints
- 1 โค user1_id, user2_id โค 105
- 1 โค page_id โค 105
- 1 โค Number of friendships โค 5 ร 104
- 1 โค Number of likes โค 105
- Each friendship is unique and bidirectional
- Each user-page like is unique
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code