
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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public static void Main(string[] args) {
6 int[,] pairs = new int[,] {
7 {1, 1}, {1, 1}, {1, 1},
8 {1, 2}, {1, 2},
9 {2, 1}, {2, 1}
10 };
11
12 Dictionary<(int, int), int> pairCount = new Dictionary<(int, int), int>();
13 for (int i = 0; i < pairs.GetLength(0); i++) {
14 var actorDirector = (pairs[i, 0], pairs[i, 1]);
15 if (pairCount.ContainsKey(actorDirector)) {
16 pairCount[actorDirector]++;
17 } else {
18 pairCount[actorDirector] = 1;
19 }
20 }
21
22 Console.WriteLine("+-------------+-------------+");
23 Console.WriteLine("| actor_id | director_id |");
24 Console.WriteLine("+-------------+-------------+");
25 foreach (var entry in pairCount) {
26 if (entry.Value >= 3) {
27 Console.WriteLine($"| {entry.Key.Item1,11} | {entry.Key.Item2,11} |");
28 }
29 }
30 }
31}This C# solution uses a Dictionary with tuples as keys to track how many times each actor-director pair appears. As with other languages, we iterate through the pairs and update the dictionary, printing any pairs that appear at least three 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.