Given three integer arrays arr1, arr2 and arr3sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays.
publicclassSolution {
public List<Integer>findCommonElements(int[] arr1, int[] arr2, int[] arr3) {
int i = 0, j = 0, k = 0;
List<Integer> commonElements =new ArrayList<>();
while (i < arr1.length&& j < arr2.length&& k < arr3.length) {
// If all three pointers have the same value, add it to the resultif (arr1[i]== arr2[j]&& arr2[j]== arr3[k]) {
commonElements.add(arr1[i]);
i++;
j++;
k++;
// Move the pointer in the smallest value } elseif (arr1[i]< arr2[j]) {
i++;
} elseif (arr2[j]< arr3[k]) {
j++;
} else {
k++;
}
}
return commonElements;
}
}
classSolution:
deffindCommonElements(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
i, j, k =0, 0, 0 common_elements = []
while i < len(arr1) and j < len(arr2) and k < len(arr3):
# If all three pointers have the same value, add it to the resultif arr1[i] == arr2[j] == arr3[k]:
common_elements.append(arr1[i])
i +=1 j +=1 k +=1# Move the pointer in the smallest valueelif arr1[i] < arr2[j]:
i +=1elif arr2[j] < arr3[k]:
j +=1else:
k +=1return common_elements
We can use count array to count all the numbers, and when the frequency becomes 3, we have found a number. WE can create a frequency array of size 2001, as in constraint we have 2000 elements.
classSolution:
defarraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
count = {}
result = []
# Count frequency of each element in arr1for x in arr1:
if x in count:
count[x] +=1else:
count[x] =1# Count frequency of each element in arr2for x in arr2:
if x in count:
count[x] +=1else:
count[x] =1# Check elements in arr3 and if their count reaches 3, add to resultfor x in arr3:
if x in count and count[x] ==2:
result.append(x)
return result