Actors and Directors Who Cooperated At Least Three Times — LeetCode 1050 Python Solution

EasyDatabase
Problem
#1050
Reading time
2 min

The problem

Report every pair of an actor and a director who have worked together at least three times, in any order. The ActorDirector table has one row per collaboration: actor_id (int), director_id (int) and timestamp (int, the primary key).

Example

ActorDirector table:

| actor_id | director_id | timestamp |
| -------- | ----------- | --------- |
| 5        | 9           | 101       |
| 5        | 9           | 102       |
| 5        | 9           | 103       |
| 5        | 12          | 104       |
| 7        | 9           | 105       |

Result:

| actor_id | director_id |
| -------- | ----------- |
| 5        | 9           |

Actor 5 and director 9 share three rows and qualify, while the other two pairings appear once each.

Python solution

Python
import pandas as pd

def actors_and_directors(actor_director: pd.DataFrame) -> pd.DataFrame:
    counts = actor_director.groupby(['actor_id', 'director_id']).size().reset_index(name='n')
    return counts[counts['n'] >= 3][['actor_id', 'director_id']]

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1050. Actors and Directors Who Cooperated At Least Three Times?
LeetCode 1050. Actors and Directors Who Cooperated At Least Three Times is rated Easy on LeetCode.
What topics does LeetCode 1050. Actors and Directors Who Cooperated At Least Three Times cover?
LeetCode 1050. Actors and Directors Who Cooperated At Least Three Times is tagged Database on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview