Strong Friendship — LeetCode 1949 Python Solution

MediumLeetCode PremiumDatabase
Problem
#1949
Reading time
5 min

Table schema

SQL
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 the users user1_id and user2_id are friends.

Example

SQL
+-------------+------+
| 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 the users user1_id and user2_id are friends.
Note that user1_id < user2_id.

Python solution

Python
import duckdb
import pandas as pd

def solution(friendship: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Friendship", friendship)
    return con.execute("""WITH
    t AS (
        SELECT
            *
        FROM Friendship
        UNION ALL
        SELECT
            user2_id,
            user1_id
        FROM Friendship
    )
SELECT
    t1.user1_id,
    t1.user2_id,
    COUNT(1) AS common_friend
FROM
    t AS t1
    JOIN t AS t2 ON t1.user2_id = t2.user1_id
    JOIN t AS t3 ON t1.user1_id = t3.user1_id
WHERE t3.user2_id = t2.user2_id AND t1.user1_id < t1.user2_id
GROUP BY t1.user1_id, t1.user2_id
HAVING COUNT(1) >= 3;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1949. Strong Friendship?
LeetCode 1949. Strong Friendship is rated Medium on LeetCode.
What topics does LeetCode 1949. Strong Friendship cover?
LeetCode 1949. Strong Friendship is tagged Database on LeetCode.
Is LeetCode 1949. Strong Friendship a premium problem?
Yes. LeetCode 1949. Strong Friendship 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