All the Pairs With the Maximum Number of Common Followers — LeetCode 1951 Python Solution
MediumLeetCode PremiumDatabase
- Problem
- #1951
- Reading time
- 4 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(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.