Leetcodify Similar Friends — LeetCode 1919 Python Solution

HardLeetCode PremiumDatabase
Problem
#1919
Reading time
3 min

Table schema

SQL
Table: Listens +-------------+---------+ | Column Name | Type | +-------------+---------+ | user_id | int | | song_id | int | | day | date | +-------------+---------+ This table may contain duplicate rows. Each row of this table indicates that the user user_id listened to the song song_id on the day day.

Example

SQL
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| user_id     | int     |
| song_id     | int     |
| day         | date    |
+-------------+---------+
This table may contain duplicate rows.
Each row of this table indicates that the user user_id listened to the song song_id on the day day.

Python solution

Python
import duckdb
import pandas as pd

def solution(listens: pd.DataFrame, friendship: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Listens", listens)
    con.register("Friendship", friendship)
    return con.execute("""SELECT DISTINCT user1_id, user2_id
FROM
    Friendship AS f
    LEFT JOIN Listens AS l1 ON user1_id = l1.user_id
    LEFT JOIN Listens AS l2 ON user2_id = l2.user_id
WHERE l1.song_id = l2.song_id AND l1.day = l2.day
GROUP BY 1, 2, l1.day
HAVING COUNT(DISTINCT l1.song_id) >= 3;""").df()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1919. Leetcodify Similar Friends?
LeetCode 1919. Leetcodify Similar Friends is rated Hard on LeetCode.
What topics does LeetCode 1919. Leetcodify Similar Friends cover?
LeetCode 1919. Leetcodify Similar Friends is tagged Database on LeetCode.
Is LeetCode 1919. Leetcodify Similar Friends a premium problem?
Yes. LeetCode 1919. Leetcodify Similar Friends is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview