Open In App

Intersection of two Arrays

Last Updated : 04 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  1. Initialize an empty array for result.
  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 result, then add it to the result.
  3. 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(' '));

Output
2 3 

[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).

  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.

[Expected Approach 1] - Using Two Hash Sets - O(n+m) Time and O(n) Space

  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 <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(" "));

Output
3 2 

[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(" "));

Output
3 2 

Related Articles:


Next Article
Article Tags :
Practice Tags :

Similar Reads