HardNo. 1919LeetCode Premium

Leetcodify Similar Friends — LeetCode 1919 Python Solution

Topics
Database
Reading time
3 min

Table schema

SQLTable schema
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

SQLExample
+-------------+---------+
| 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

PythonSolution
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

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium
0180Consecutive NumbersMedium
0181Employees Earning More Than Their ManagersEasy

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.

Free to download. Check it runs on your machine, then pick a plan.