This problem asks to find the intersection of three sorted arrays, meaning the numbers that appear in all three arrays. The solution can be approached in a couple of ways: using counting or using binary search.
This approach uses a frequency count to efficiently determine which numbers appear in all three arrays.
Algorithm:
arr1
, arr2
, arr3
), incrementing the count for each number encountered in the frequency counter.Time Complexity: O(N), where N is the total number of elements across all three arrays. This is because we iterate through each array once.
Space Complexity: O(M), where M is the range of numbers (2001 in this specific problem). This is the space used by the frequency counter. If we used a hash map, the space complexity would be O(K) where K is the number of unique elements.
Code (Python):
from collections import Counter
class Solution:
def arraysIntersection(self, arr1: list[int], arr2: list[int], arr3: list[int]) -> list[int]:
cnt = Counter(arr1 + arr2 + arr3)
return [x for x in arr1 if cnt[x] == 3]
Code (Java):
import java.util.*;
class Solution {
public List<Integer> arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
List<Integer> ans = new ArrayList<>();
int[] cnt = new int[2001]; // Since numbers are in range [1, 2000]
for (int x : arr1) cnt[x]++;
for (int x : arr2) cnt[x]++;
for (int x : arr3) {
cnt[x]++;
if (cnt[x] == 3) ans.add(x);
}
return ans;
}
}
This approach uses binary search to efficiently check if a number exists in the other two arrays.
Algorithm:
arr1
.arr2
and arr3
to check if it exists.arr2
and arr3
, add it to the result list.Time Complexity: O(N log N), where N is the maximum length among the three arrays. This is because we iterate through one array (O(N)) and perform binary search on the others (O(log N) each).
Space Complexity: O(1), as we are using only a constant amount of extra space.
Code (Python):
import bisect
class Solution:
def arraysIntersection(self, arr1: list[int], arr2: list[int], arr3: list[int]) -> list[int]:
ans = []
for x in arr1:
if bisect.bisect_left(arr2, x) < len(arr2) and arr2[bisect.bisect_left(arr2, x)] == x and \
bisect.bisect_left(arr3, x) < len(arr3) and arr3[bisect.bisect_left(arr3, x)] == x:
ans.append(x)
return ans
Code (Java):
import java.util.*;
class Solution {
public List<Integer> arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
List<Integer> ans = new ArrayList<>();
for (int x : arr1) {
int i = Arrays.binarySearch(arr2, x);
int j = Arrays.binarySearch(arr3, x);
if (i >= 0 && j >= 0) ans.add(x);
}
return ans;
}
}
The counting approach is generally preferred for this problem due to its linear time complexity, making it more efficient for larger input arrays. The binary search approach is a viable alternative, but its logarithmic time complexity improvement doesn't outweigh the constant factor overhead for reasonably sized inputs.