Skip to main content

LeetCode 1919. Leetcodify Similar Friends SQL Solution

Problem

LeetCode SQL Problem

  1. Leetcodify Similar Friends

Listens table

user_idsong_idday
1102021-03-15 00:00:00
1112021-03-15 00:00:00
1122021-03-15 00:00:00
2102021-03-15 00:00:00
2112021-03-15 00:00:00
2122021-03-15 00:00:00
3102021-03-15 00:00:00
3112021-03-15 00:00:00
3122021-03-15 00:00:00
4102021-03-15 00:00:00
4112021-03-15 00:00:00
4132021-03-15 00:00:00
5102021-03-16 00:00:00
5112021-03-16 00:00:00
5122021-03-16 00:00:00

Friendship table

user1_iduser2_id
12
24
25

Solution

MySQL Solution to report users who listened to the same three or more different songs on the same day.
WITH song_listened_analysis
AS (
-- Perform Self Join so we can detect user_id pairs that listened to the same song on the same day
SELECT A.user_id AS user_x
,B.user_id AS user_y
-- Only count the same song once
,count(DISTINCT A.song_id) AS same_song_count
FROM Listens AS A
INNER JOIN Listens AS B ON A.user_id < B.user_id
AND A.day = B.day
AND A.song_id = B.song_id
GROUP BY A.user_id
,B.user_id
-- Only return user_id pairs that listened to the same three or more different songs on the same day.
HAVING same_song_count >= 3
)
-- INNER JOIN Friendship table so we only return user_id pairs that are friends
SELECT F.*
FROM song_listened_analysis AS SLA
INNER JOIN Friendship AS F ON (
SLA.user_x = F.user1_id
AND SLA.user_y = F.user2_id
);

Query Output

user1_iduser2_id
12