Strong Friendship — LeetCode 1949 Python Solution
MediumLeetCode PremiumDatabase
- Problem
- #1949
- Reading time
- 5 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(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.