Actors and Directors Who Cooperated At Least Three Times solution and explanation
9 more videos on this problem
LeetCode Interview SQL Question with Detailed Explanation | Practice SQL | LeetCode 1050Everyday Data Science · 5:36 · 14K views
米开:LeetCode 1050. Actors and Directors Who Cooperated At Least Three TimesM.C米开朗基罗 · 6:08 · 321 views
SQL Interview Question #9 | Actors And Directors Who Cooperated Atleast 3 Times | Leetcode SQL 1050Sarthak Dasgupta · 4:26 · 269 views
1050. Actors and Directors Who Cooperated At Least Three Times leetcode solution | realNameHiddenrealNameHidden · 6:13 · 167 views
1050. Actors and Directors who Cooperated 3 Times | LeetCode | SQL | Solution | Interview ProblemData Alchemist · 3:44 · 124 views
LeetCode 1050 | Actors and Directors Who Cooperated At Least Three Times | Group by | SQLSleepy Cracker · 2:00 · 84 views
LeetCode DB Problem: 1050. Actors and Directors who cooperated at least three timesEden Boychyn · 2:12 · 83 views
Actors and Directors Who Cooperated At Least Three Times || Leetcode SQL QuestionCodeInQueries · 4:44 · 47 views
MySQL - Leetcode 1050 Walkthrough- Actors and Directors Who Cooperated At Least Three TimesChristopher Chapman · 7:25 · 38 views
【Leetcode Pandas 19/30】1050. Actors and Directors Who Cooperated At Least Three Times (~Easy)思臉AI · 1:48 · 35 views
The problem
Table: ActorDirector
+-------------+---------+ | Column Name | Type | +-------------+---------+ | actor_id | int | | director_id | int | | timestamp | int | +-------------+---------+ timestamp is the primary key (column with unique values) for this table.
Write a solution to find all the pairs (actor_id, director_id) where the actor has cooperated with the director at least three times.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input: ActorDirector table: +-------------+-------------+-------------+ | actor_id | director_id | timestamp | +-------------+-------------+-------------+ | 1 | 1 | 0 | | 1 | 1 | 1 | | 1 | 1 | 2 | | 1 | 2 | 3 | | 1 | 2 | 4 | | 2 | 1 | 5 | | 2 | 1 | 6 | +-------------+-------------+-------------+ Output: +-------------+-------------+ | actor_id | director_id | +-------------+-------------+ | 1 | 1 | +-------------+-------------+ Explanation: The only pair is (1, 1) where they cooperated exactly 3 times.
Approach overview
Problem Overview: You are given a table that records collaborations between actors and directors. Each row contains an actor_id and a director_id. The task is to return all pairs that have worked together at least three times.
Approach 1: Using a HashMap to Count Occurrences (Time: O(n), Space: O(n))
Iterate through each row and treat the pair (actor_id, director_id) as a key. Store the count of collaborations in a hash map. Every time the same pair appears again, increment the stored value. After processing all rows, iterate through the map and collect pairs where the count is greater than or equal to three.
The key insight is that collaboration pairs repeat across rows. A hash map provides constant-time lookup and updates, which makes counting efficient. This approach works well if you are processing the dataset in application code (Python, Java, C++, etc.) instead of directly querying the database.
Approach 2: Using SQL GROUP BY and HAVING Clause (Time: O(n), Space: O(1) additional)
Group the rows by actor_id and director_id using the SQL GROUP BY clause. For each group, compute the number of rows using COUNT(*). Then filter the results with a HAVING COUNT(*) >= 3 condition to keep only pairs that collaborated at least three times.
This approach pushes the counting work to the database engine. Modern SQL engines optimize grouping and aggregation very efficiently. It is the most natural solution for database problems and avoids transferring unnecessary data into application memory.
Because the dataset is already stored in a relational table, grouping and aggregation through SQL is both concise and performant.
Recommended for interviews: The SQL GROUP BY with HAVING solution is what interviewers typically expect for database questions. It demonstrates understanding of aggregation and filtering directly in SQL. The hash map approach is still valuable when the data is processed in application code or when practicing algorithmic counting patterns.
Approach 1: Approach 1: Using a HashMap to Count Occurrences
This approach involves iterating through the given table and using a hash map (or dictionary) to count how many times each actor-director pair appears. After counting, you can filter these pairs to only include those that have a count of three or more.
from collections import defaultdict
def find_pairs(actor_director):
pair_count = defaultdict(int)
for pair in actor_director:
pair_count[(pair[0], pair[1])] += 1
print('+-------------+-------------+')
print('| actor_id | director_id |')
print('+-------------+-------------+')
for pair, count in pair_count.items():
if count >= 3:
print(f'| {pair[0]:11} | {pair[1]:11} |')
pairs = [
(1, 1), (1, 1), (1, 1),
(1, 2), (1, 2),
(2, 1), (2, 1)
]
find_pairs(pairs)import java.util.*;
public class Solution {
public static void main(String[] args) {
int[][] actorDirector = {
{1, 1}, {1, 1}, {1, 1},
{1, 2}, {1, 2},
{2, 1}, {2, 1}
};
Map<List<Integer>, Integer> pairCount = new HashMap<>();
for (int[] pair : actorDirector) {
List<Integer> list = Arrays.asList(pair[0], pair[1]);
pairCount.put(list, pairCount.getOrDefault(list, 0) + 1);
}
System.out.println("+-------------+-------------+");
System.out.println("| actor_id | director_id |");
System.out.println("+-------------+-------------+");
for (Map.Entry<List<Integer>, Integer> entry : pairCount.entrySet()) {
if (entry.getValue() >= 3) {
System.out.printf("| %11d | %11d |\n", entry.getKey().get(0), entry.getKey().get(1));
}
}
}
}#include <iostream>
#include <unordered_map>
#include <utility>
using namespace std;
typedef pair<int, int> Pair;
int main() {
unordered_map<Pair, int, hash<Pair>> pairCount;
Pair pairs[] = {
{1, 1}, {1, 1}, {1, 1},
{1, 2}, {1, 2},
{2, 1}, {2, 1}
};
int size = sizeof(pairs) / sizeof(pairs[0]);
for (int i = 0; i < size; ++i) {
pairCount[pairs[i]]++;
}
cout << "+-------------+-------------+\n";
cout << "| actor_id | director_id |\n";
cout << "+-------------+-------------+\n";
for (auto &entry : pairCount) {
if (entry.second >= 3)
cout << "| " << entry.first.first << " | " << entry.first.second << " |\n";
}
return 0;
}const pairs = [
[1, 1], [1, 1], [1, 1],
[1, 2], [1, 2],
[2, 1], [2, 1]
];
const pairCount = new Map();
pairs.forEach(([actorId, directorId]) => {
const key = `${actorId},${directorId}`;
pairCount.set(key, (pairCount.get(key) || 0) + 1);
});
console.log('+-------------+-------------+');
console.log('| actor_id | director_id |');
console.log('+-------------+-------------+');
pairCount.forEach((count, key) => {
if (count >= 3) {
const [actorId, directorId] = key.split(',').map(Number);
console.log(`| ${actorId.toString().padStart(11)} | ${directorId.toString().padStart(11)} |`);
}
});#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 1000
typedef struct Pair {
int actor_id;
int director_id;
} Pair;
typedef struct Node {
Pair pair;
int count;
struct Node* next;
} Node;
Node* hashMap[TABLE_SIZE] = {NULL};
unsigned int hash(Pair pair) {
return (pair.actor_id * 31 + pair.director_id) % TABLE_SIZE;
}
void insertOrIncrement(Pair pair) {
unsigned int index = hash(pair);
Node* node = hashMap[index];
while (node != NULL) {
if (node->pair.actor_id == pair.actor_id && node->pair.director_id == pair.director_id) {
node->count++;
return;
}
node = node->next;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->pair = pair;
newNode->count = 1;
newNode->next = hashMap[index];
hashMap[index] = newNode;
}
void findPairs(Pair* pairs, int size) {
for (int i = 0; i < size; ++i) {
insertOrIncrement(pairs[i]);
}
printf("+-------------+-------------+\n");
printf("| actor_id | director_id |\n");
printf("+-------------+-------------+\n");
for (int i = 0; i < TABLE_SIZE; ++i) {
Node* node = hashMap[i];
while (node != NULL) {
if (node->count >= 3) {
printf("| %11d | %11d |\n", node->pair.actor_id, node->pair.director_id);
}
node = node->next;
}
}
}
int main() {
Pair pairs[] = {
{1, 1}, {1, 1}, {1, 1},
{1, 2}, {1, 2},
{2, 1}, {2, 1}
};
int size = sizeof(pairs) / sizeof(pairs[0]);
findPairs(pairs, size);
return 0;
}using System;
using System.Collections.Generic;
public class Solution {
public static void Main(string[] args) {
int[,] pairs = new int[,] {
{1, 1}, {1, 1}, {1, 1},
{1, 2}, {1, 2},
{2, 1}, {2, 1}
};
Dictionary<(int, int), int> pairCount = new Dictionary<(int, int), int>();
for (int i = 0; i < pairs.GetLength(0); i++) {
var actorDirector = (pairs[i, 0], pairs[i, 1]);
if (pairCount.ContainsKey(actorDirector)) {
pairCount[actorDirector]++;
} else {
pairCount[actorDirector] = 1;
}
}
Console.WriteLine("+-------------+-------------+");
Console.WriteLine("| actor_id | director_id |");
Console.WriteLine("+-------------+-------------+");
foreach (var entry in pairCount) {
if (entry.Value >= 3) {
Console.WriteLine($"| {entry.Key.Item1,11} | {entry.Key.Item2,11} |");
}
}
}
}This Python solution uses a defaultdict from the collections module to store the occurrence count of each actor-director pair. The dictionary is updated while iterating, and pairs with a count of three or more are printed.
Time Complexity: O(n), since dictionary operations such as insert and lookup in Python are on average O(1).
Space Complexity: O(m), where m represents the number of unique actor-director pairs.
Approach 2: Approach 2: Using SQL Group By and Having Clause
If this were a SQL-based system, an efficient way to find the actors and directors who have cooperated at least three times is by using SQL's GROUP BY and HAVING clauses. The GROUP BY clause allows us to group rows that have the same values in specified columns, while the HAVING clause will filter these groups based on a given condition.
SELECT actor_id, director_id
FROM ActorDirector
GROUP BY actor_id, director_id
HAVING COUNT(*) >= 3;In this SQL solution, we group the entries in the ActorDirector table by actor_id and director_id. The HAVING clause ensures that only pairs with three or more entries in the table are selected for the final result.
Time Complexity: O(n log n), due to potential sorting in the GROUP BY operation.
Space Complexity: O(k), where k is the number of groups formed from distinct pairs of actors and directors.
Complexity comparison
| Approach | Complexity |
|---|---|
| Approach 1: Using a HashMap to Count Occurrences | Time Complexity: O(n), since dictionary operations such as insert and lookup in Python are on average O(1). |
| Approach 2: Using SQL Group By and Having Clause | Time Complexity: O(n log n), due to potential sorting in the GROUP BY operation. |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| HashMap Counting | O(n) | O(n) | When processing collaboration data in application code rather than directly in SQL |
| SQL GROUP BY + HAVING | O(n) | O(1) additional | Best for database queries where aggregation and filtering can be handled by the SQL engine |
Frequently asked questions
Is Actors and Directors Who Cooperated At Least Three Times easy or hard?
The problem is categorized as Easy. It mainly tests understanding of SQL aggregation with GROUP BY and HAVING or simple frequency counting with a hash map, both of which are fundamental concepts.
Actors and Directors Who Cooperated At Least Three Times Python/Java solution
In Python or Java, iterate through each record and store counts in a hash map keyed by (actor_id, director_id). Increment the count for each occurrence and collect pairs where the count is at least three. The approach runs in O(n) time and O(n) space.
How to solve Actors and Directors Who Cooperated At Least Three Times in O(n)?
Scan all rows and count occurrences of each (actor_id, director_id) pair. In SQL, use GROUP BY actor_id, director_id and filter with HAVING COUNT(*) >= 3. In programming languages, store counts in a hash map and return pairs whose count reaches three or more.
What is the best approach for Actors and Directors Who Cooperated At Least Three Times?
The most efficient approach is using SQL GROUP BY with a HAVING COUNT(*) >= 3 condition. It groups rows by actor_id and director_id and directly filters pairs that collaborated at least three times. This runs in O(n) time and leverages database aggregation efficiently.
Is Actors and Directors Who Cooperated At Least Three Times asked at Google/Amazon/Meta?
This problem is a typical SQL aggregation question similar to those used in database interviews at companies like Amazon, Meta, and Google. It tests knowledge of GROUP BY, HAVING, and basic data aggregation rather than complex algorithms.
What data structure is used in Actors and Directors Who Cooperated At Least Three Times?
The algorithmic version uses a hash map where the key is the pair (actor_id, director_id) and the value is the collaboration count. In SQL solutions, the database internally handles grouping using aggregation structures during the GROUP BY operation.
What is the time complexity of Actors and Directors Who Cooperated At Least Three Times?
The typical solution runs in O(n) time where n is the number of rows in the ActorDirector table. SQL engines scan the table and aggregate counts per (actor_id, director_id) pair. Hash map implementations in application code also run in O(n) time with O(n) space.
