Intersection of two Arrays (original) (raw)

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.

Table of Content

[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:

#include #include using namespace std;

vector intersect(vector& a, vector& b) { vector 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 a = {1, 2, 3, 2, 1}; vector 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 intersect(int[] a, int[] b) { List res = new List();

    // 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:

  1. Initialize an empty hash set for storing result array elements
  2. 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.
  3. Create a result array and copy items of the hash set to the result array and return the result array. C++ `

#include #include #include using namespace std;

vector intersect(vector& a, vector& b) { vector 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 a = {1, 2, 3, 2, 1}; vector 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 intersect(int[] a, int[] b) { ArrayList 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 intersect(int[] a, int[] b) { List res = new List(); 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:

  1. Initialize an empty array for result
  2. 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]
  3. Create an empty hash set for result rs (Set of result elements)
  4. Create an empty array res[] to store result
  5. Traverse through all items of b[]. If an item is in as and not in rs, then add it to res[] and rs
  6. Return res[] C++ `

#include #include #include using namespace std;

vector intersect(vector& a, vector& 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 a = {1, 2, 3, 2, 1}; vector 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 intersect(ArrayList a, ArrayList 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 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 #include #include using namespace std;

vector intersect(vector& a, vector& 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 a = {1, 2, 3, 2, 1}; vector 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 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: