Find Intersection of Two Arrays in C++
In this tutorial, we will learn how to find the intersection of two arrays in C++. Before that let’s first understand what is array.
Array: is a derived data type that contains the same type of data. Like integer array stores values of only integer type, float array stores values of only float type.
Derived data type: is a data type that is defined by the user itself. Other derived data types are Structure, Class, Union, Enumeration, and Pointers.
The intersection of two arrays: is the set of all elements of A that also belong to B (or vice versa).
Example:
Array1: { 1, 2, 3, 4, 5 }
Array2: { 4, 5, 6, 7, 8, 9, 10 }
The intersection of given two arrays: { 4, 5 }. Because elements 4 and 5 are common in both the arrays.
(*Note: Array should not contain 1 element twice.)
Program to Find Intersection of Two Arrays in C++
#include<iostream> using namespace std; int main() { int n1,n2,i,j; cout<<"Enter the no. of elements of the 1st array: "; cin>>n1; /* declaring arr1 of size n1 */ int arr1[n1]; /* Enter distinct elements */ cout<<"Enter the elements of the 1st array: "; for(i=0;i<n1;i++) { cin>>arr1[i]; } cout<<"\nEnter the no. of elements of the 2nd array: "; cin>>n2; /* declaring arr2 of size n2 */ int arr2[n2]; /* Enter distinct elements */ cout<<"Enter the elements of the 2nd array: "; for(i=0;i<n2;i++) { cin>>arr2[i]; } /* printing elements that are common in both the arrays */ cout<<"\nThe intersection of the two arrays: "; for(i=0;i<n1;i++) { for(j=0;j<n2;j++) { if(arr1[i]==arr2[j]) { cout<<arr1[i]<<" "; } } } return 0; }
Input/Output:
Enter the no. of elements of the 1st array: 5 Enter the elements of the 1st array: -4 1 3 0 8 Enter the no. of elements of the 2nd array: 8 Enter the elements of the 2nd array: 3 -7 -4 9 6 0 17 5 The intersection of the two arrays: -4 3 0
Time Complexity
O(n1*n2), where n1 is the no. of elements of the first array and n2 is no. of elements of the second array.
You may also read:
does intersection contains duplicate values ,if not then this logic may be wrong for this condition :
n1=6
n2=4
arr1=1,5,6,9,8,5
arr2=8,9,5,1
then their output will be 1,5,9,8,5 and here 5 comes two times.
void intersection(int *input1, int *input2, int size1, int size2)
{
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
if (input1[i] == input2[j])
{
cout << input1[i] << " ";
input2[j] = INT_MIN;
break;
}
}
}
}
for a1=6 2 6 2 1 9 8
for a2=3 6 8 2 9
for this output is comin wrong