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.
1#include <iostream>
2#include <unordered_map>
3#include <utility>
4
5using namespace std;
6
7typedef pair<int, int> Pair;
8
9int main() {
10 unordered_map<Pair, int, hash<Pair>> pairCount;
11 Pair pairs[] = {
12 {1, 1}, {1, 1}, {1, 1},
13 {1, 2}, {1, 2},
14 {2, 1}, {2, 1}
15 };
16 int size = sizeof(pairs) / sizeof(pairs[0]);
17 for (int i = 0; i < size; ++i) {
18 pairCount[pairs[i]]++;
19 }
20 cout << "+-------------+-------------+\n";
21 cout << "| actor_id | director_id |\n";
22 cout << "+-------------+-------------+\n";
23 for (auto &entry : pairCount) {
24 if (entry.second >= 3)
25 cout << "| " << entry.first.first << " | " << entry.first.second << " |\n";
26 }
27 return 0;
28}
This C++ solution uses an unordered_map
to count each pair's occurrences. The map's keys are pairs of integers, and its values are the count of these pairs. We iterate through pairs, updating the map, and finally filter and display pairs that appeared three or more times.
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.