Get uncommon elements from two sorted arrays in C++
In this tutorial, we will be learning about how to get uncommon elements from two sorted arrays in C++.
Approach 1
The sample example code is as follows…
#include <iostream> #include<bits/stdc++.h> using namespace std; int main() { int n,m; cout<<"Enter the array size of two arrays\n"; cin>>m>>n; int arr1[m],arr2[n]; cout<<"Enter the sorted array elements\n"; for(int i=0;i<m;i++) { cin>>arr1[i]; } for(int i=0;i<n;i++) { cin>>arr2[i]; } cout<<"\nThe Uncommmon elements are : "; vector<int>v; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(arr1[i]==arr2[j]) v.push_back(arr1[i]); } } std::vector<int>::iterator it; for(int i=0;i<m;i++) { it=std::find(v.begin(),v.end(),arr1[i]); if(it==v.end()) cout<<arr1[i]<<" "; } for(int i=0;i<n;i++) { it=std::find(v.begin(),v.end(),arr2[i]); if(it==v.end()) cout<<arr2[i]<<" "; } return 0; }
Output :
Enter the array size of two arrays 3 5 Enter the sorted array elements 1 2 3 3 4 1 5 6 The Uncommmon elements are : 2 4 5 6
Explanation :
- Here first, we need to take the size of two sorted arrays from the user.
- Then the user needs to enter the elements of two sorted arrays.
- Then here we have declared a vector so that the common elements are pushed into it.
- Then by running the two separate for loops we need to print the elements which are not in the vector.
Approach 2
The sample example code is as follows…
#include <iostream> #include<bits/stdc++.h> using namespace std; int main() { int n,m; cout<<"Enter the array size of two arrays\n"; cin>>m>>n; int arr1[m],arr2[n]; map<int,int>mp; cout<<"Enter the sorted array elements\n"; for(int i=0;i<m;i++) { cin>>arr1[i]; mp[arr1[i]]++; } for(int i=0;i<n;i++) { cin>>arr2[i]; mp[arr2[i]]++; } cout<<"The Uncommon elements are : "; for(auto it :mp) { if(it.second==1) cout<<it.first<<" "; } return 0; }
Output :
Enter the array size of two arrays 5 7 Enter the sorted array elements 1 4 6 7 8 1 2 3 4 5 6 7 The Uncommon elements are : 2 3 5 8
Explanation :
- Generally, here we need to take the sizes of two sorted arrays.
- Then we need to take the elements of two sorted arrays.
- Then here we have used a map data structure for storing the elements and their occurrence( key as element and value as its count of occurrence).
- At last, we need to return the element(key) whose value is equal to one.
Leave a Reply