본문 바로가기
Data Analysis/SQL Pandas

leetcode : 1729. Find Followers Count

by 베짱이28호 2025. 2. 6.

leetcode : 1729. Find Followers Count


다이어그램

erDiagram
    FOLLOWS {
        int user_id PK
        int follower_id PK
    }
  • 각 유져별로 팔로워 수를 구한다

 

문제 풀이

MySQL

SELECT USER_ID, COUNT(*) AS FOLLOWERS_COUNT
FROM FOLLOWERS
GROUP BY USER_ID
ORDER BY USER_ID
  • 단순 GROUP BY + COUNT 문제

MySQL 2

SELECT USER_ID, COUNT(DISTINCT FOLLOWER_ID) AS FOLLOWERS_COUNT
FROM FOLLOWERS
GROUP BY USER_ID
  • 중복 팔로잉이 존재할거같아서 COUNT DISTINCT를 사용했다.

Pandas 1

import pandas as pd

def count_followers(followers: pd.DataFrame) -> pd.DataFrame:
    grouped = followers.groupby('user_id').agg(
        followers_count = ('follower_id','size')
    ).reset_index()
    return grouped
  • 단순 group by + count문제

Pandas 2

def count_followers(followers: pd.DataFrame) -> pd.DataFrame:

    grouped = followers.groupby(by=['user_id']).agg(
        followers_count = ('follower_id','nunique')
        ).reset_index()
    return grouped
  • 중복 id가 발생하는걸 고려해서 nunique를 썼는데 정답은 똑같다.

 

코멘트

  • 쉬운문제

댓글