#1264
Medium Database Page recommendations
Database
65.4% acceptance
Mar 31, 2026
266
27
No description available.
Solution
Pandas
Time O(n)
Space O(1)
# Table: Friendship
#
# +---------------+---------+
# | Column Name | Type |
# +---------------+---------+
# | user1_id | int |
# | user2_id | int |
# +---------------+---------+
# (user1_id, user2_id) is the primary key (combination of columns with unique values) for this table.
# Each row of this table indicates that there is a friendship relation between user1_id and user2_id.
#
#
#
# Table: Likes
#
# +-------------+---------+
# | Column Name | Type |
# +-------------+---------+
# | user_id | int |
# | page_id | int |
# +-------------+---------+
# (user_id, page_id) is the primary key (combination of columns with unique values) for this table.
# Each row of this table indicates that user_id likes page_id.
#
#
#
# Write a solution to recommend pages to the user with user_id = 1 using the pages that your friends liked. It should not recommend pages you already liked.
#
# Return result table in any order without duplicates.
#
# The result format is in the following example.
#
# Example 1:
# Input:
# Friendship table:
# +----------+----------+
# | user1_id | user2_id |
# +----------+----------+
# | 1 | 2 |
# | 1 | 3 |
# | 1 | 4 |
# | 2 | 3 |
# | 2 | 4 |
# | 2 | 5 |
# | 6 | 1 |
# +----------+----------+
# Likes table:
# +---------+---------+
# | user_id | page_id |
# +---------+---------+
# | 1 | 88 |
# | 2 | 23 |
# | 3 | 24 |
# | 4 | 56 |
# | 5 | 11 |
# | 6 | 33 |
# | 2 | 77 |
# | 3 | 77 |
# | 6 | 88 |
# +---------+---------+
# Output:
# +------------------+
# | recommended_page |
# +------------------+
# | 23 |
# | 24 |
# | 56 |
# | 33 |
# | 77 |
# +------------------+
# Explanation:
# User one is friend with users 2, 3, 4 and 6.
# Suggested pages are 23 from user 2, 24 from user 3, 56 from user 3 and 33 from user 6.
# Page 77 is suggested from both user 2 and user 3.
# Page 88 is not suggested because user 1 already likes it.
import pandas as pd
def page_recommendations(friendship: pd.DataFrame, likes: pd.DataFrame) -> pd.DataFrame:
# Find friends of user 1
friends1 = friendship[friendship['user1_id'] == 1]['user2_id']
friends2 = friendship[friendship['user2_id'] == 1]['user1_id']
friends = pd.concat([friends1, friends2]).unique()
# Pages liked by friends
friend_pages = likes[likes['user_id'].isin(friends)]['page_id'].unique()
# Pages already liked by user 1
my_pages = likes[likes['user_id'] == 1]['page_id'].unique()
# Recommend pages not already liked
recommended = set(friend_pages) - set(my_pages)
return pd.DataFrame({'recommended_page': sorted(recommended)})