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.
1const pairs = [
2 [1, 1], [1, 1], [1, 1],
3 [1, 2], [1, 2],
4 [2, 1], [2, 1]
5];
6
7const pairCount = new Map();
8pairs.forEach(([actorId, directorId]) => {
9 const key = `${actorId},${directorId}`;
10 pairCount.set(key, (pairCount.get(key) || 0) + 1);
11});
12
13console.log('+-------------+-------------+');
14console.log('| actor_id | director_id |');
15console.log('+-------------+-------------+');
16pairCount.forEach((count, key) => {
17 if (count >= 3) {
18 const [actorId, directorId] = key.split(',').map(Number);
19 console.log(`| ${actorId.toString().padStart(11)} | ${directorId.toString().padStart(11)} |`);
20 }
21});
This JavaScript solution utilizes a Map
to store the count of actor-director pairs. Keys are strings ("actorId,directorId") that allow us to effectively hash each pair and keep a tally. Once counted, we output pairs that have been seen 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.