![]() |
VOOZH | about |
Given two arrays a[] and b[] with distinct elements of size n and m respectively, the task is to find intersection (or common elements) of the two arrays. We can return the answer in any order.
Note: Intersection of two arrays can be defined as a set containing distinct common elements between the two arrays.
Examples:
Input: a[] = { 5, 6, 2, 1, 4 }, b[] = { 7, 9, 4, 2 }
Output: { 2, 4 }
Explanation: The only common elements in both arrays are 2 and 4.
Input: a[] = { 4, 5, 2, 3 } , b[] = { 1, 7 }
Output: { }
Explanation: There are no common elements in array a[] and b[]
Table of Content
The idea is to traverse the first array a[] and for each element from a[], check whether it is present in array b[]. If present then add this element to result array.
2 4
Time Complexity : O(n*m), where n and m are size of array a[] and b[] respectively.
Auxiliary Space : O(1)
The idea is to sort both the arrays and then maintain a pointer at the beginning of each array. By comparing the elements at both pointers, we can decide how to proceed:
- If the element in the first array is smaller than the one in the second, move the pointer in the first array forward, because that element can't be part of the intersection.
- If the element in the first array is greater, move the second pointer forward.
- If the two elements are equal, you add that element to the result and move both pointers forward.
This continues until one of the pointers reaches the end of its array.
To know more about the implementation of this approach, please refer the post Intersection of Two Sorted Arrays with Distinct Elements.
The idea is to use a hash set to store the elements of array a[]. Then, go through array b[] and check if each element is present in the hash set. If an element is found in the hash set, add it to the result array since it is common in both the arrays.
4 2
Time Complexity: O(n + m), where n and m are size of array a[] and b[] respectively.
Auxiliary Space: O(n)
Related Articles: