Last Updated : 27 Jul, 2025
Try it on GfG Practice
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.
[Naive Approach] Using Triple Nested Loops - O(n × n × m) Time and O(1) SpaceInput: 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 elementsInput: 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.
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:
#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:
#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:
#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
C++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.
#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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4