How to find the intersection of two arrays in C++

Overview

The union of two sets, A and B, is the set of elements in A,B, or in both A and B.

Set has a property in which all the elements in the set are unique.

Example

A = {3,5,7 8,4,9} 
B = {1,2,3,5,9,7,8,6}

A ∩ B = { 3, 5, 9, 7, 8 }

Code

#include <iostream>
using namespace std;
#define sizeOfA 6
#define sizeOfB 8
int findCommonElement(int setA[], int sizeOfSetA, int setB[], int sizeOfSetB)
{
int commonElemnt =0;
for(int i=0; i<sizeOfSetA; i++)
{
for(int j=0; j<sizeOfSetB; j++)
{
if(setA[i]==setB[j])
{
commonElemnt++;
}
}
}
}
int *findIntersection(int setA[], int sizeOfSetA, int setB[], int sizeOfSetB, int commonElement)
{
int *IntersectionArray;
// find size of new Array
int sizeOfIntersectionArray= commonElement;
IntersectionArray= new int[sizeOfIntersectionArray];
int k=0; // to insert elemnt in the union array we use this iterator
for(int i=0; i<sizeOfSetB; i++)
{
for(int j=0; j<sizeOfSetA; j++)
{
if (setA[j]==setB[i])
{
IntersectionArray[k]=setA[j];
k++;
}
}
}
return IntersectionArray;
}
int main()
{
int * IntersectionArray;
// declare two array A and B
int A[sizeOfA] = {3,5,7,8,4,9};
int B[sizeOfB] = {1,2,3,5,9,7,8,6};
int commonElement=findCommonElement(A,sizeOfA, B,sizeOfB);// get number of Common Element of both arrays
int sizeOfNewArray=commonElement-1;// calculate size ofnew Array
IntersectionArray=findIntersection(A,sizeOfA,B,sizeOfB, commonElement);
//Print the array element
cout<<"{ ";
for(int i =0; i<sizeOfNewArray; i++)
{
if(i==sizeOfNewArray-1)
{
cout<<IntersectionArray[i]<<" }";
}
else
{
cout<<IntersectionArray[i]<<", ";
}
}
return 0;
}

Explanation

  • Line 3 and 4: We define the size of setA and setB.
  • Line 5 to 18: We define the function findCommonElement that can find the count of the common elements between two sets.
  • Line 19 to 39: We define the function findIntersection that can find the intersection of two set setA and setB.
  • Line 44 and 45: We define two arrays, setA and setB.
  • Line 48: We call the function findIntersection and save the array return by function in the IntersectionArray pointer variable.
  • Line 50 to 62: We print the intersection of setA and setB.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved