Intersection of two Arrays
Last Updated :
04 Oct, 2024
Given two arrays a[] and b[], the task is find intersection of the two arrays. Intersection of two arrays is said to be elements that are common in both arrays. The intersection should not count duplicate elements and the result should contain items in any order.
Input: a[] = {1, 2, 1, 3, 1}, b[] = {3, 1, 3, 4, 1}
Output: {1, 3}
Explanation: 1 and 3 are the only common elements and we need to print only one occurrence of common elements
Input: a[] = {1, 1, 1}, b[] = {1, 1, 1, 1, 1}
Output: {1}
Explanation: 1 is the only common element present in both the arrays.
Input: a[] = {1, 2, 3}, b[] = {4, 5, 6}
Output: {}
Explanation: No common element in both the arrays.
[Naive Approach] Using Triple Nested Loops - O(n*n*m) Time and O(1) Space
- Initialize an empty array for result.
- Traverse through a[] and for every element check if it is in b[], then check if it is already in result or not. If in b[] and not in result, then add it to the result.
- Return result.
C++
#include <iostream>
#include <vector>
using namespace std;
vector<int> intersection(vector<int>& a, vector<int>& b) {
vector<int> res;
// Traverse through a[] and search every element
// a[i] in b[]
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < b.size(); j++) {
// If found, check if the element is already
// in the result to avoid duplicates
if (a[i] == b[j]) {
int k;
for (k = 0; k < res.size(); k++)
if (res[k] == a[i])
break;
if (k == res.size()) {
res.push_back(a[i]);
}
}
}
}
return res;
}
int main() {
vector<int> a = {1, 2, 3, 2, 1};
vector<int> b = {3, 2, 2, 3, 3, 2};
vector<int> res = intersection(a, b);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
C
#include <stdio.h>
// Function to find intersection of two arrays
void intersection(int a[], int n1, int b[], int n2, int res[], int *res_size) {
// Traverse through a[] and search every element a[i] in b[]
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
// If found, check if the element is already in the result
int found = 0;
if (a[i] == b[j]) {
for (int k = 0; k < *res_size; k++) {
if (res[k] == a[i]) {
found = 1;
break;
}
}
if (!found) {
res[(*res_size)++] = a[i];
}
}
}
}
}
int main() {
int a[] = {1, 2, 3, 2, 1};
int b[] = {3, 2, 2, 3, 3, 2};
int res[10];
int res_size = 0;
intersection(a, 5, b, 6, res, &res_size);
for (int i = 0; i < res_size; i++) {
printf("%d ", res[i]);
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to find intersection of two arrays
static List<Integer> intersection(int[] a, int[] b) {
List<Integer> res = new ArrayList<>();
// Traverse through a[] and search every element a[i] in b[]
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
// If found, check if the element is already in the result
if (a[i] == b[j]) {
if (!res.contains(a[i])) {
res.add(a[i]);
}
}
}
}
return res;
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 2, 1};
int[] b = {3, 2, 2, 3, 3, 2};
List<Integer> res = intersection(a, b);
for (int val : res) {
System.out.print(val + " ");
}
}
}
Python
# Function to find intersection of two arrays
def intersection(a, b):
res = []
# Traverse through a[] and search every element a[i] in b[]
for i in a:
for j in b:
# If found, check if the element is already in the result
if i == j and i not in res:
res.append(i)
return res
# Driver code
a = [1, 2, 3, 2, 1]
b = [3, 2, 2, 3, 3, 2]
res = intersection(a, b)
print(" ".join(map(str, res)))
C#
using System;
using System.Collections.Generic;
class GfG
{
// Function to find intersection of two arrays
static List<int> intersection(int[] a, int[] b)
{
List<int> res = new List<int>();
// Traverse through a[] and search every element a[i] in b[]
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < b.Length; j++)
{
// If found, check if the element is already in the result
if (a[i] == b[j] && !res.Contains(a[i]))
{
res.Add(a[i]);
}
}
}
return res;
}
static void Main()
{
int[] a = { 1, 2, 3, 2, 1 };
int[] b = { 3, 2, 2, 3, 3, 2 };
List<int> res = intersection(a, b);
foreach (int val in res)
{
Console.Write(val + " ");
}
}
}
JavaScript
// Function to find intersection of two arrays
function intersection(a, b) {
let res = [];
// Traverse through a[] and search every element a[i] in b[]
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < b.length; j++) {
// If found, check if the element is already in the result
if (a[i] === b[j] && !res.includes(a[i])) {
res.push(a[i]);
}
}
}
return res;
}
// Driver code
let a = [1, 2, 3, 2, 1];
let b = [3, 2, 2, 3, 3, 2];
let res = intersection(a, b);
console.log(res.join(' '));
[Better Approach] Using Nested Loops and Hash Set - O(n*m) Time and O(n) Space
One obvious optimization is to use a Hash Set for result so that we can reduce the time complexity to O(n^2).
- Initialize an empty hash set for storing result array elements
- Traverse through a[] and for every element check if it is in b[], then check if it is already in result or not. If in b[] and not in the hash set, then add it to the hash set.
- Create a result array and copy items of the hash set to the result array and return the result array.
[Expected Approach 1] - Using Two Hash Sets - O(n+m) Time and O(n) Space
- Initialize an empty array for result
- Create a hash set as (Set of a[] elements) and put all distinct items of a[] into it. For example, if array is {1, 2, 1, 3, 1}, as is going to store [1, 2, 3]
- Create an empty hash set for result rs (Set of result elements)
- Create an empty array res[] to store result
- Traverse through all items of b[]. If an item is in as and not in rs, then add it to res[] and rs
- Return res[]
C++
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
vector<int> intersection(vector<int>& a, vector<int>& b) {
// Put all elements of a[] in as
unordered_set<int> as(a.begin(), a.end());
unordered_set<int> rs;
vector<int> res;
// Traverse through b[]
for (int i = 0; i < b.size(); i++) {
// If the element is in as and not yet in rs
// a) Add it to the result set
// b) Add it to the result array
if (as.find(b[i]) != as.end() &&
rs.find(b[i]) == rs.end()) {
rs.insert(b[i]);
res.push_back(b[i]);
}
}
return res;
}
int main() {
vector<int> a = {1, 2, 3, 2, 1};
vector<int> b = {3, 2, 2, 3, 3, 2};
vector<int> res = intersection(a, b);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
import java.util.*;
class GfG {
static List<Integer> intersection(List<Integer> a, List<Integer> b) {
// Put all elements of a[] in as
Set<Integer> as = new HashSet<>(a);
Set<Integer> rs = new HashSet<>();
List<Integer> res = new ArrayList<>();
// Traverse through b[]
for (int i = 0; i < b.size(); i++) {
// If the element is in as and not yet in rs
// a) Add it to the result set
// b) Add it to the result array
if (as.contains(b.get(i)) &&
!rs.contains(b.get(i))) {
rs.add(b.get(i));
res.add(b.get(i));
}
}
return res;
}
public static void main(String[] args) {
List<Integer> a = Arrays.asList(1, 2, 3, 2, 1);
List<Integer> b = Arrays.asList(3, 2, 2, 3, 3, 2);
List<Integer> res = intersection(a, b);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
}
Python
# Function to find intersection of two arrays
def intersection(a, b):
# Put all elements of a[] in as
as_set = set(a)
rs_set = set()
res = []
# Traverse through b[]
for elem in b:
# If the element is in as_set and not yet in rs_set
if elem in as_set and elem not in rs_set:
rs_set.add(elem)
res.append(elem)
return res
# Driver code
a = [1, 2, 3, 2, 1]
b = [3, 2, 2, 3, 3, 2]
res = intersection(a, b)
print(" ".join(map(str, res)))
C#
using System;
using System.Collections.Generic;
class GfG
{
// Function to find intersection of two arrays
static List<int> intersection(int[] a, int[] b)
{
// Put all elements of a[] in as
HashSet<int> asSet = new HashSet<int>(a);
HashSet<int> rsSet = new HashSet<int>();
List<int> res = new List<int>();
// Traverse through b[]
foreach (int num in b)
{
// If the element is in as and not yet in rs
if (asSet.Contains(num) && !rsSet.Contains(num))
{
rsSet.Add(num);
res.Add(num);
}
}
return res;
}
static void Main()
{
int[] a = { 1, 2, 3, 2, 1 };
int[] b = { 3, 2, 2, 3, 3, 2 };
List<int> res = intersection(a, b);
foreach (int val in res)
{
Console.Write(val + " ");
}
}
}
JavaScript
// Function to find intersection of two arrays
function intersection(a, b) {
// Put all elements of a[] in as
const asSet = new Set(a);
const rsSet = new Set();
const res = [];
// Traverse through b[]
for (let i = 0; i < b.length; i++) {
// If the element is in asSet and not yet in rsSet
if (asSet.has(b[i]) && !rsSet.has(b[i])) {
rsSet.add(b[i]);
res.push(b[i]);
}
}
return res;
}
// Driver code
let a = [1, 2, 3, 2, 1];
let b = [3, 2, 2, 3, 3, 2];
let res = intersection(a, b);
console.log(res.join(" "));
[Expected Approach 2] Using One Hash Set - O(n+m) Time and O(n) Space
We optimize the above approach by avoiding creation of rs hash set. To make sure that duplicates are not added, we simply delete items from as (Set of a[] elements) rather than checking with rs.
C++
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
vector<int> intersection(vector<int>& a, vector<int>& b) {
// Put all elements of a[] in sa
unordered_set<int> sa(a.begin(), a.end());
vector<int> res;
// Traverse through b[]
for (int i = 0; i < b.size(); i++) {
// If the element is in sa
// a) Add it to the result array
// b) Erase it from sa to avoid duplicates
if (sa.find(b[i]) != sa.end()) {
res.push_back(b[i]);
sa.erase(b[i]);
}
}
return res;
}
int main() {
vector<int> a = {1, 2, 3, 2, 1};
vector<int> b = {3, 2, 2, 3, 3, 2};
vector<int> res = intersection(a, b);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to find intersection of two arrays
static List<Integer> intersection(int[] a, int[] b) {
// Put all elements of a[] in sa
HashSet<Integer> sa = new HashSet<>();
for (int num : a) {
sa.add(num);
}
List<Integer> res = new ArrayList<>();
// Traverse through b[]
for (int num : b) {
// If the element is in sa
if (sa.contains(num)) {
res.add(num); // Add it to the result array
sa.remove(num); // Erase it from sa to avoid duplicates
}
}
return res;
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 2, 1};
int[] b = {3, 2, 2, 3, 3, 2};
List<Integer> res = intersection(a, b);
for (int val : res) {
System.out.print(val + " ");
}
}
}
Python
# Function to find intersection of two arrays
def intersection(a, b):
# Put all elements of a[] in sa
sa = set(a)
res = []
# Traverse through b[]
for elem in b:
# If the element is in sa
if elem in sa:
res.append(elem) # Add it to the result array
sa.remove(elem) # Erase it from sa to avoid duplicates
return res
# Driver code
a = [1, 2, 3, 2, 1]
b = [3, 2, 2, 3, 3, 2]
res = intersection(a, b)
print(" ".join(map(str, res)))
C#
using System;
using System.Collections.Generic;
class GfG
{
// Function to find intersection of two arrays
static List<int> intersection(int[] a, int[] b)
{
// Put all elements of a[] in sa
HashSet<int> sa = new HashSet<int>(a);
List<int> res = new List<int>();
// Traverse through b[]
foreach (int num in b)
{
// If the element is in sa
if (sa.Contains(num))
{
// Add it to the result array
res.Add(num);
// Erase it from sa to avoid duplicates
sa.Remove(num);
}
}
return res;
}
static void Main()
{
int[] a = { 1, 2, 3, 2, 1 };
int[] b = { 3, 2, 2, 3, 3, 2 };
List<int> res = intersection(a, b);
foreach (int val in res)
{
Console.Write(val + " ");
}
}
}
JavaScript
// Function to find intersection of two arrays
function intersection(a, b) {
// Put all elements of a[] in sa
const sa = new Set(a);
const res = [];
// Traverse through b[]
for (let i = 0; i < b.length; i++) {
// If the element is in sa
if (sa.has(b[i])) {
res.push(b[i]); // Add it to the result array
sa.delete(b[i]); // Erase it from sa to avoid duplicates
}
}
return res;
}
// Driver code
let a = [1, 2, 3, 2, 1];
let b = [3, 2, 2, 3, 3, 2];
let res = intersection(a, b);
console.log(res.join(" "));
Related Articles:
Similar Reads
Intersection of Two Sorted Arrays Given two sorted arrays a[] and b[], the task is to return intersection. Intersection of two arrays is said to be elements that are common in both arrays. The intersection should not count duplicate elements and the result should contain items in sorted order.Examples:Input: a[] = {1, 1, 2, 2, 2, 4}
12 min read
Intersection of n sets Given n sets of integers of different sizes. Each set may contain duplicates also. How to find the intersection of all the sets. If an element is present multiple times in all the sets, it should be added that many times in the result.For example, consider there are three sets {1,2,2,3,4} {2,2,3,5,6
12 min read
Intersection of Two Arrays with Distinct Elements Given two arrays a[] and b[] with distinct elements of size n and m respectively, the task is to find intersection (or common elements) of the two arrays. We can return the answer in any order.Note: Intersection of two arrays can be defined as a set containing distinct common elements between the tw
9 min read
Intersection of Two Sorted Arrays with Distinct Elements Given two sorted arrays a[] and b[] with distinct elements of size n and m respectively, the task is to find intersection (or common elements) of the two arrays. We need to return the intersection in sorted order.Note: Intersection of two arrays can be defined as a set containing distinct common ele
13 min read
Find the intersection of two Matrices Given two matrix A[][] and B[][] of same order m*n. The task is to find the intersection of both matrix as C, where: Cij = Aij if Aij = BijC = "*", otherwise. Examples: Input : A[N][N] = {{2, 4, 6, 8}, {1, 3, 5, 7}, {8, 6, 4, 2}, {7, 5, 3, 1}}; B[N][N] = {{0, 4, 3, 8}, {1, 3, 5, 7}, {8, 3, 6, 2}, {4
6 min read
std::set_intersection in C++ The intersection of two sets is formed only by the elements that are present in both sets. The elements copied by the function come always from the first range, in the same order. The elements in the both the ranges shall already be ordered.Examples: Input : 5 10 15 20 25 50 40 30 20 10 Output : The
5 min read
Union and Intersection of two Linked Lists Given two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two linked lists contains distinct node values.Note: The order of elements in output lists doesnât matter. Example:Input: head1: 10 ->
15+ min read
Union and Intersection of Two Sorted Arrays - Complete Tutorial Union of two arrays is an array having all distinct elements that are present in either array whereas Intersection of two arrays is an array containing distinct common elements between the two arrays. In this post, we will discuss about Union and Intersection of sorted arrays. To know about union an
6 min read
Intersection of intervals given by two lists Given two 2-D arrays which represent intervals. Each 2-D array represents a list of intervals. Each list of intervals is disjoint and sorted in increasing order. Find the intersection or set of ranges that are common to both the lists.Note: Disjoint means no element is common in a listExamples: Inpu
6 min read
Number of intersections between two ranges Given N ranges of type1 ranges and M ranges of type2.The task is to find the total number of intersections between all possible type1 and type2 range pairs. All start and end points of type1 and type2 ranges are given.Examples: Input : N = 2, M = 2 type1[ ] = { { 1, 3 }, { 5, 9 } } type2[ ] = { { 2,
8 min read