Intersection of two Arrays
Last Updated :
27 Jul, 2025
Given two arrays a[] and b[], find their intersection — the unique elements that appear in both. Ignore duplicates, and the result can be 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
The idea is to find all unique elements that appear in both arrays by checking each element of one array against the other and ensuring no duplicates are added to the result.
Step By Step Implementation:
- 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> intersect(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 = intersect(a, b);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
C
#include <stdio.h>
void intersect(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;
intersect(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;
class GfG {
static ArrayList<Integer> intersect(int[] a, int[] b) {
ArrayList<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};
ArrayList<Integer> res = intersect(a, b);
for (int val : res) {
System.out.print(val + " ");
}
}
}
Python
def intersect(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
if __name__ == "__main__":
a = [1, 2, 3, 2, 1]
b = [3, 2, 2, 3, 3, 2]
res = intersect(a, b)
print(" ".join(map(str, res)))
C#
using System;
using System.Collections.Generic;
class GfG {
static List<int> intersect(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 = intersect(a, b);
foreach (int val in res)
{
Console.Write(val + " ");
}
}
}
JavaScript
function intersect(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 = intersect(a, b);
console.log(res.join(' '));
[Better Approach] Using Nested Loops and Hash Set - O(n × m) Time and O(n) Space
The idea is to find common elements between two arrays without duplicates by:|
– Using a hash set to track already added elements,
– Checking each element of a[] against b[], and only adding it to the result if it's present in b[] and not already recorded.
Step By Step Implementation:
- 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.
C++
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> intersect(vector<int>& a, vector<int>& b) {
vector<int> res;
unordered_map<int, int> seen;
// 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] && seen.count(a[i]) == 0) {
seen.insert({a[i], 1});
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 = intersect(a, b);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
import java.util.ArrayList;
import java.util.HashMap;
class GfG {
static ArrayList<Integer> intersect(int[] a, int[] b) {
ArrayList<Integer> res = new ArrayList<>();
HashMap<Integer, Integer> seen = new HashMap<>();
// 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 to avoid duplicates
if (a[i] == b[j] && !seen.containsKey(a[i])) {
seen.put(a[i], 1);
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};
ArrayList<Integer> res = intersect(a, b);
for (int x : res)
System.out.print(x + " ");
}
}
Python
def intersect(a, b):
res = []
seen = {}
# Traverse through a[] and search every element
# a[i] in b[]
for i in range(len(a)):
for j in range(len(b)):
# If found, check if the element is already
# in the result to avoid duplicates
if a[i] == b[j] and a[i] not in seen:
seen[a[i]] = 1
res.append(a[i])
return res
if __name__ == "__main__":
a = [1, 2, 3, 2, 1]
b = [3, 2, 2, 3, 3, 2]
res = intersect(a, b)
for x in res:
print(x, end=" ")
C#
using System;
using System.Collections.Generic;
class GfG {
static List<int> intersect(int[] a, int[] b) {
List<int> res = new List<int>();
Dictionary<int, int> seen = new Dictionary<int, 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 to avoid duplicates
if (a[i] == b[j] && !seen.ContainsKey(a[i])) {
seen[a[i]] = 1;
res.Add(a[i]);
}
}
}
return res;
}
static void Main(string[] args) {
int[] a = {1, 2, 3, 2, 1};
int[] b = {3, 2, 2, 3, 3, 2};
List<int> res = intersect(a, b);
foreach (int x in res)
Console.Write(x + " ");
}
}
JavaScript
function intersect(a, b) {
let res = [];
let seen = {};
// 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 to avoid duplicates
if (a[i] === b[j] && !(a[i] in seen)) {
seen[a[i]] = 1;
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 = intersect(a, b);
for (let i = 0; i < res.length; i++)
console.log(res[i]);
[Expected Approach 1] Using Two Hash Sets - O(n+m) Time and O(n) Space
The idea is to use hash sets to efficiently find the unique elements that are common to both arrays. One set (as) stores elements from the first array, and the other (rs) ensures each common element is added only once to the result.
Step By Step Implementations:
- 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> intersect(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 = intersect(a, b);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
class GfG {
static ArrayList<Integer> intersect(ArrayList<Integer> a,
ArrayList<Integer> b) {
// Put all elements of a[] in as
Set<Integer> as = new HashSet<>(a);
Set<Integer> rs = new HashSet<>();
ArrayList<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) {
ArrayList<Integer> a = new ArrayList<>(Arrays.asList(1, 2, 3, 2, 1));
ArrayList<Integer> b = new ArrayList<>(Arrays.asList(3, 2, 2, 3, 3, 2));
ArrayList<Integer> res = intersect(a, b);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
}
Python
def intersect(a, b):
# Put all elements of a[] in asSet
asSet = set(a)
rsSet = set()
res = []
# Traverse through b[]
for elem in b:
# If the element is in
# asSet and not yet in rsSet
if elem in asSet and elem not in rsSet:
rsSet.add(elem)
res.append(elem)
return res
if __name__ == "__main__":
a = [1, 2, 3, 2, 1]
b = [3, 2, 2, 3, 3, 2]
res = intersect(a, b)
print(" ".join(map(str, res)))
C#
using System;
using System.Collections.Generic;
class GfG {
static List<int> intersect(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 = intersect(a, b);
foreach (int val in res)
{
Console.Write(val + " ");
}
}
}
JavaScript
function intersect(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 = intersect(a, b);
console.log(res.join(" "));
[Expected Approach 2] Using One Hash Set - O(n+m) Time and O(n) Space
We can 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> intersect(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 = intersect(a, b);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
import java.util.HashSet;
import java.util.ArrayList;
class GfG {
// Function to find intersection of two arrays
static ArrayList<Integer> intersect(int[] a, int[] b) {
// Put all elements of a[] in sa
HashSet<Integer> sa = new HashSet<>();
for (int num : a) {
sa.add(num);
}
ArrayList<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};
ArrayList<Integer> res = intersect(a, b);
for (int val : res) {
System.out.print(val + " ");
}
}
}
Python
def intersect(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:
# Add it to the result array
res.append(elem)
# Erase it from sa to avoid duplicates
sa.remove(elem)
return res
if __name__ == "__main__":
a = [1, 2, 3, 2, 1]
b = [3, 2, 2, 3, 3, 2]
res = intersect(a, b)
print(" ".join(map(str, res)))
C#
using System;
using System.Collections.Generic;
class GfG {
static List<int> intersect(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 = intersect(a, b);
foreach (int val in res)
{
Console.Write(val + " ");
}
}
}
JavaScript
function intersect(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])) {
// Add it to the result array
res.push(b[i]);
// Erase it from sa to avoid duplicates
sa.delete(b[i]);
}
}
return res;
}
// Driver code
let a = [1, 2, 3, 2, 1];
let b = [3, 2, 2, 3, 3, 2];
let res = intersect(a, b);
console.log(res.join(" "));
Related Articles:
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem