![]() |
VOOZH | about |
Given two sorted arrays a[] and b[]. The task is to return the common elements of both arrays. If an element appears more than once in both array, we need to pick minimum of its two frequencies
Examples:
Input: a[] = [1, 1, 2, 2, 2, 4], b[] = [2, 2, 4, 4]
Output: [2, 2, 4]
Explanation: 2 and 4 are only common elements and 2 appears two times in both arrays.Input: a[] = [1, 2], b[] = [3, 4]
Output: []
Explanation: No common elements.Input: a[] = [1, 1, 1], b[] = [1, 1, 1, 1]
Output: [1, 1, 1]
Table of Content
We have discussed different approaches for common of two unsorted arrays. We can use the same approaches here. The best performance that we can achieve using the same approaches is O(n) Time and O(n) Auxiliary Space for hash set. Please note that in these approaches we do not use the fact that input arrays are sorted,
The idea is based one merge function to merge two sorted arrays.
1 2 4
Input : a = {1, 2, 2, 2, 3}, b = {2, 2, 4}
Initialization:
i = 0,j = 0,res = []ipoints to elements in arraya[]andjpoints to elements in arrayb[].Iterations inside the while loop:
1st Iteration:
a[i] = 1,b[j] = 2a[i]is smaller, so skip the smaller element ina[].i = 1,j = 02nd Iteration:
a[i] = 2,b[j] = 2- Since
a[i]is equal tob[j], both arrays have this common element. So we keep adding to result while matching.- res = [2, 2]
- i = 3, j = 2
3rd Iteration:
a[i] = 2,b[j] = 4- Since
a[i]is smaller thanb[j], skip the smaller element ina[]by incrementingi.- Update:
i = 4,j = 24th Iteration:
a[i] = 3,b[j] = 4- Since
a[i]is smaller thanb[j], skip the smaller element ina[]by incrementingi.- Update:
i = 5,j = 2