![]() |
VOOZH | about |
Given two sorted 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 need to return the intersection in sorted order.
Note: Intersection of two arrays can be defined as a set containing distinct common elements between the two arrays.
Examples:
Input: a[] = { 1, 2, 4, 5, 6 }, b[] = { 2, 4, 7, 9 }
Output: { 2, 4 }
Explanation: The common elements in both arrays are 2 and 4.
Input: a[] = { 2, 3, 4, 5 }, b[] = { 1, 7 }
Output: { }
Explanation: There are no common elements in array a[] and b[].
Table of Content
The idea is to use the same approaches as discussed in Intersection of Two Arrays with Distinct Elements. The most optimal approach among them is to use Hash Set which has a time complexity of O(n+m) and Auxiliary Space of O(n).
The idea is to find the intersection of two sorted arrays using merge step of merge sort. We maintain two pointers to traverse both arrays simultaneously.
- If the element in first array is smaller, move the pointer of first array forward because this element cannot be part of the intersection.
- If the element in second array is smaller, move the pointer of second array forward.
- If both elements are equal, add one of them and move both the pointers forward.
This continues until one of the pointers reaches the end of its 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 check each element of array a[] and see if it is in array b[]. If it is, we add it to the result array. Since b[] is already sorted, we can use binary search to find the elements in log(n) time.
2 4
Time Complexity: O(n * log (m)), where n and m are size of array a[] and b[] respectively.
Auxiliary Space: O(1)
Related Articles: