![]() |
VOOZH | about |
Here we will build a C Program to Find Common Array Elements between Two Arrays. Given two arrays we have to find common elements in them using the below 2 approaches:
Input:
array1[] = {8, 2, 3, 4, 5, 6, 7, 1}
array2[] = {4, 5, 7, 11, 6, 1}
Output:
Common elements are: 4 5 6 7 1
This is a brute force approach, simply traverse in the first array, for every element of the first array traverse in the second array to find whether it exists there or not, if true then check it in the result array (to avoid repetition), after that if we found that this element is not present in result array then print it and store it in the result array.
Common elements are: 4 5 6 7 1
Time Complexity: O(m*n*k)
Auxiliary Space: O(max(m,n)), as in worst case all the elements could be distinct and common.
This logic can be applied to the sorted array, if the sorted array is not given then sort it using merge sort as its time complexity is less and then apply this approach.
Common elements are: 2 5 7 18
Time Complexity: O((m+n)*k)
Auxiliary Space: O(max(m,n)), as in worst case all the elements could be distinct and common.