Page Recommendations LeetCode Solution

Last updated on October 9th, 2024 at 10:12 pm

This Leetcode problem Page Recommendations LeetCode Solution is done in SQL.

List of all LeetCode Solution

Level of Question

Medium

Page Recommendations LeetCode Solution

Page Recommendations LeetCode Solution

Problem Statement

Column NameType
user1_idint
user2_idint
Table: Friendship

(user1_id, user2_id) is the primary key for this table.
Each row of this table indicates that there is a friendship relation between user1_id and user2_id.

Column NameType
user_idint
page_idint
Table: Likes

(user_id, page_id) is the primary key for this table.
Each row of this table indicates that user_id likes page_id.

Write an SQL query 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:

user1_iduser2_id
12
13
14
23
24
25
61
Friendship table:
user_idpage_id
188
223
324
456
511
633
277
377
688
Likes table:

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.

1. Page Recommendations LeetCode Solution MySQL

select 
  distinct page_id as recommended_page 
from 
  Likes as l 
  left join Friendship as f on f.user2_id = l.user_id 
where 
  f.user1_id = 1 
  and page_id not in (
    select 
      page_id 
    from 
      Likes 
    where 
      user_id = 1
  ) 
union 
select 
  distinct page_id as recommended_page 
from 
  Likes as l 
  left join Friendship as f on f.user1_id = l.user_id 
where 
  f.user2_id = 1 
  and page_id not in (
    select 
      page_id 
    from 
      Likes 
    where 
      user_id = 1
  );
Scroll to Top