01 Common elements
Using map
Logic
For each element
xinarr1Store
xin map and mark it as 1
For each element
yinarr2andymarked as 1 in mapmark
yas 2 in map
For each element
zinarr3andzmarked as 2 in mapStore
zinresult
return
result
Code
vector <int> commonElements (int A[], int B[], int C[], int n1, int n2, int n3)
{
map<int, int> visited;
// mark present in arr1 as 1
for(int i = 0; i < n1; i++)
visited[A[i]] = 1;
// mark present in arr2 and marked 1 as 2
for(int j = 0; j < n2; j++)
if(visited[B[j]] == 1)
visited[B[j]] = 2;
// mark present in arr2 and marked 2 as 3
for(int z = 0; z < n3; z++)
if(visited[C[z]] == 2)
visited[C[z]] = 3;
// all those marked as 3 are present in all the three arrays
vector<int> intersection;
for(auto p: visited)
if(p.second == 3)
intersection.push_back(p.first);
return intersection;
}Using 3 pointers
Logic
Take the pointer
p1,p2,p3for each arrayIf
p1is the smallest element, then increment it (same forp2andp3)At some point, all
p1,p2,p3are the same.Check if the currently pointed item is not already in the result vector
If so, insert it into the result vector and increment the three pointers.
As soon as one of the pointers exhausts its corresponding array, stop.
Code
vector <int> commonElements (int A[], int B[], int C[], int n1, int n2, int n3)
{
int p1 = 0, p2 = 0, p3 = 0;
vector<int> res;
while(p1 < n1 && p2 < n2 && p3 < n3) {
if(A[p1] == B[p2] && B[p2] == C[p3]) {
if(res.empty() || res.back() != A[p1])
res.push_back(A[p1]);
p1++, p2++, p3++;
}
else if(A[p1] <= B[p2] && A[p1] <= C[p3])
p1++;
else if(B[p2] <= C[p3])
p2++;
else
p3++;
}
return res;
}Last updated