All the Pairs With the Maximum Number of Common Followers — LeetCode 1951 Python Solution

MediumLeetCode PremiumDatabase
Problem
#1951
Reading time
4 min

Table schema

SQL
Table: Relations +-------------+------+ | Column Name | Type | +-------------+------+ | user_id | int | | follower_id | int | +-------------+------+ (user_id, follower_id) is the primary key (combination of columns with unique values) for this table. Each row of this table indicates that the user with ID follower_id is following the user with ID user_id.

Example

SQL
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id     | int  |
| follower_id | int  |
+-------------+------+
(user_id, follower_id) is the primary key (combination of columns with unique values) for this table.
Each row of this table indicates that the user with ID follower_id is following the user with ID user_id.

Python solution

Python
import duckdb
import pandas as pd

def solution(relations: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Relations", relations)
    return con.execute("""WITH
    t AS (
        SELECT
            r1.user_id AS user1_id,
            r2.user_id AS user2_id,
            RANK() OVER (ORDER BY COUNT(1) DESC) AS rk
        FROM
            Relations AS r1
            JOIN Relations AS r2 ON r1.follower_id = r2.follower_id AND r1.user_id < r2.user_id
        GROUP BY r1.user_id, r2.user_id
    )
SELECT
    user1_id,
    user2_id
FROM t
WHERE rk = 1;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1951. All the Pairs With the Maximum Number of Common Followers?
LeetCode 1951. All the Pairs With the Maximum Number of Common Followers is rated Medium on LeetCode.
What topics does LeetCode 1951. All the Pairs With the Maximum Number of Common Followers cover?
LeetCode 1951. All the Pairs With the Maximum Number of Common Followers is tagged Database on LeetCode.
Is LeetCode 1951. All the Pairs With the Maximum Number of Common Followers a premium problem?
Yes. LeetCode 1951. All the Pairs With the Maximum Number of Common Followers 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