susinlee 님의 블로그

117. Friend Requests II: Who Has the Most Friends 본문

코드카타/SQL, Pandas

117. Friend Requests II: Who Has the Most Friends

susinlee 2025. 2. 10. 09:32

[문제]

https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/description/

 

[풀이]

1. requester_id 열과 accepter_id 열을 위 아래로 합쳐준다.

2. 합친 열을 그룹화하고 개수를 센다음 정렬한 뒤 제일 첫 번째 행을 가져온다.

 

Pandas

import pandas as pd

def most_friends(request_accepted: pd.DataFrame) -> pd.DataFrame:
    df = pd.DataFrame({
        'id': pd.concat([request_accepted['requester_id'], request_accepted['accepter_id']])
    })

    return df.groupby('id').size().reset_index("id").rename(columns={0:'num'}).sort_values('num', ascending=False).iloc[[0]]

 

SQL

# Write your MySQL query statement below
WITH grouped_id AS (
    SELECT requester_id AS id FROM RequestAccepted
    UNION ALL
    SELECT accepter_id AS id FROM RequestAccepted
)
SELECT
    id
    , COUNT(*) AS num
FROM grouped_id
GROUP BY id
ORDER BY num DESC
LIMIT 1

'코드카타 > SQL, Pandas' 카테고리의 다른 글

119. Department Top Three Salaries  (0) 2025.02.27
118. Investments in 2016  (0) 2025.02.25
SQL 윈도우 함수 구조  (0) 2025.02.09
116. Restaurant Growth  (0) 2025.02.09
115. Movie Rating  (0) 2025.01.30