
Sponsored
Sponsored
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.
Time Complexity: O(n), where n is the number of entries in the table.
Space Complexity: O(m), where m is the number of distinct actor-director pairs.
1from collections import defaultdict
2
3def find_pairs(actor_director):
4 pair_count = defaultdict(int)
5 for pair in actor_director:
6 pair_count[(pair[0], pair[1])] += 1
7
8 print('+-------------+-------------+')
9 print('| actor_id | director_id |')
10 print('+-------------+-------------+')
11 for pair, count in pair_count.items():
12 if count >= 3:
13 print(f'| {pair[0]:11} | {pair[1]:11} |')
14
15pairs = [
16 (1, 1), (1, 1), (1, 1),
17 (1, 2), (1, 2),
18 (2, 1), (2, 1)
19]
20
21find_pairs(pairs)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.
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.
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.
1SELECT actor_id, director_id
2FROM ActorDirector
3GROUP BY actor_id,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.