MediumNo. 1951LeetCode Premium
All the Pairs With the Maximum Number of Common Followers — LeetCode 1951 Python Solution
- Topics
- Database
- Reading time
- 4 min
- Source
- leetcode.com
Table schema
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
+-------------+------+
| 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
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
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0175 | Combine Two Tables | Easy |
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
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.