Open In App

Intersection of Two Arrays with Distinct Elements

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

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 two arrays.

Examples:

Input: a[] = { 5, 6, 2, 1, 4 }, b[] = { 7, 9, 4, 2 }
Output: { 2, 4 }
Explanation: The only common elements in both arrays are 2 and 4.

Input: a[] = { 4, 5, 2, 3 } , b[] = { 1, 7 }
Output: { }
Explanation: There are no common elements in array a[] and b[]

[Naive Approach] Using nested loop - O(n*m) Time and O(1) Space

The idea is to traverse the first array a[] and for each element from a[], check whether it is present in array b[]. If present then add this element to result array.

C++
// C++ program for intersection of two arrays with
// distinct elements using nested loops

#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 in b[], then add this
          	// element to result array
            if (a[i] == b[j]) { 
              	res.push_back(a[i]);
              	break;
            }
        }
    }

    return res;
}

int main() {
    vector<int> a = {5, 6, 2, 1, 4}; 
    vector<int> b = {7, 9, 4, 2};

    vector<int> res = intersection(a, b);
  
    for (int i = 0; i < res.size(); i++) 
        cout << res[i] << " ";

    return 0;
}
C
// C program for intersection of two arrays with
// distinct elements using nested loops

#include <stdio.h>

int* intersection(int a[], int n, int b[], int m, int* resSize) {
    int* res = (int*)malloc(100 * sizeof(int)); 
    *resSize = 0;      
  	
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (a[i] == b[j]) {
                res[(*resSize)++] = a[i];
                break;
            }
        }
    }

    return res;
}

int main() {
    int a[] = {5, 6, 2, 1, 4};
    int b[] = {7, 9, 4, 2};
    int resSize;
    
    int* res = intersection(a, 5, b, 4, &resSize);

    for (int i = 0; i < resSize; i++) {
        printf("%d ", res[i]);
    }

    return 0;
}
Java
// Java program for intersection of two arrays with
// distinct elements using nested loops

import java.util.ArrayList;

class GfG {
    static ArrayList<Integer> intersection(int[] a, int[] b) {
        ArrayList<Integer> res = new ArrayList<>();

        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < b.length; j++) {
                if (a[i] == b[j]) {
                    res.add(a[i]);
                    break;
                }
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] a = {5, 6, 2, 1, 4};
        int[] b = {7, 9, 4, 2};

        ArrayList<Integer> res = intersection(a, b);

        for (int num : res) {
            System.out.print(num + " ");
        }
    }
}
Python
# Python program for intersection of two arrays with
# distinct elements using nested loops

def intersection(a, b):
    res = []

    for i in range(len(a)):
        for j in range(len(b)):
            if a[i] == b[j]:
                res.append(a[i])
                break

    return res

if __name__ == "__main__":
    a = [5, 6, 2, 1, 4]
    b = [7, 9, 4, 2]

    res = intersection(a, b)

    for num in res:
        print(num, end=" ")
C#
// C# program for intersection of two arrays with
// distinct elements using nested loops

using System;
using System.Collections.Generic;

class GfG {
    static List<int> intersection(int[] a, int[] b) {
        List<int> res = new List<int>();

        for (int i = 0; i < a.Length; i++) {
            for (int j = 0; j < b.Length; j++) {
                if (a[i] == b[j]) {
                    res.Add(a[i]);
                    break;
                }
            }
        }

        return res;
    }

    static void Main() {
        int[] a = {5, 6, 2, 1, 4};
        int[] b = {7, 9, 4, 2};

        List<int> res = intersection(a, b);

        foreach (int num in res) {
            Console.Write(num + " ");
        }
    }
}
JavaScript
// JavaScript program for intersection of two arrays with
// distinct elements using nested loops

function intersection(a, b) {
    let res = [];

    for (let i = 0; i < a.length; i++) {
        for (let j = 0; j < b.length; j++) {
            if (a[i] === b[j]) {
                res.push(a[i]);
                break;
            }
        }
    }

    return res;
}

let a = [5, 6, 2, 1, 4];
let b = [7, 9, 4, 2];

let res = intersection(a, b);

console.log(res.join(" "));

Output
2 4 

Time Complexity : O(n*m), where n and m are size of array a[] and b[] respectively.
Auxiliary Space : O(1)

[Better Approach] Using Sorting and Two Pointers - O(n*logm) Time and O(1) Space

The idea is to sort both the arrays and then maintain a pointer at the beginning of each array. By comparing the elements at both pointers, we can decide how to proceed:

  • If the element in the first array is smaller than the one in the second, move the pointer in the first array forward, because that element can't be part of the intersection.
  • If the element in the first array is greater, move the second pointer forward.
  • If the two elements are equal, you add that element to the result and move both pointers forward.

This continues until one of the pointers reaches the end of its array.

To know more about the implementation of this approach, please refer the post Intersection of Two Sorted Arrays with Distinct Elements.

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

The idea is to use a hash set to store the elements of array a[]. Then, go through array b[] and check if each element is present in the hash set. If an element is found in the hash set, add it to the result array since it is common in both the arrays.

C++
// C++ program for intersection of two arrays with
// distinct elements using hash set

#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 hash set
    unordered_set<int> st(a.begin(), a.end());  
    vector<int> res;                            
    for (int i = 0; i < b.size(); i++) {
      
        // If the element is in st
        // then add it to result array
        if (st.find(b[i]) != st.end()) {
            res.push_back(b[i]); 
        }
    }

    return res;
}

int main() {
    vector<int> a = {5, 6, 2, 1, 4}; 
    vector<int> b = {7, 9, 4, 2};

    vector<int> res = intersect(a, b);
    for (int i = 0; i < res.size(); i++) 
        cout << res[i] << " ";

    return 0;
}
Java
// Java program for intersection of two arrays with
// distinct elements using hash set

import java.util.*;

class GfG {
    static ArrayList<Integer> intersect(int[] a, int[] b) {
      	
        // Put all elements of a[] in hash set
        HashSet<Integer> st = new HashSet<>();
        for (int num : a) {
            st.add(num);
        }
        ArrayList<Integer> res = new ArrayList<>();
        for (int i = 0; i < b.length; i++) {
          
            // If the element is in st
            // then add it to result array
            if (st.contains(b[i])) {
                res.add(b[i]);
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] a = {5, 6, 2, 1, 4};
        int[] b = {7, 9, 4, 2};

        ArrayList<Integer> res = intersect(a, b);
        for (int num : res) {
            System.out.print(num + " ");
        }
    }
}
Python
# Python program for intersection of two arrays with
# distinct elements using hash set

def intersect(a, b):
  
    # Put all elements of a[] in hash set
    st = set(a)
    res = []
    for i in range(len(b)):
      
        # If the element is in st
        # then add it to result array
        if b[i] in st:
            res.append(b[i])

    return res

if __name__ == "__main__":
    a = [5, 6, 2, 1, 4]
    b = [7, 9, 4, 2]

    res = intersect(a, b)
    for num in res:
        print(num, end=" ")
C#
// C# program for intersection of two arrays with
// distinct elements using hash set

using System;
using System.Collections.Generic;

class GfG {
    static List<int> intersect(int[] a, int[] b) {
      
        // Put all elements of a[] in hash set
        HashSet<int> st = new HashSet<int>(a);
        List<int> res = new List<int>();
        for (int i = 0; i < b.Length; i++) {
          
            // If the element is in st
            // then add it to result array
            if (st.Contains(b[i])) {
                res.Add(b[i]);
            }
        }

        return res;
    }

    static void Main() {
        int[] a = {5, 6, 2, 1, 4};
        int[] b = {7, 9, 4, 2};

        List<int> res = intersect(a, b);
        foreach (int num in res) {
            Console.Write(num + " ");
        }
    }
}
JavaScript
// JavaScript program for intersection of two arrays with
// distinct elements using hash set

function intersect(a, b) {
  
    // Put all elements of a[] in hash set
    let st = new Set(a);
    let res = [];
    for (let i = 0; i < b.length; i++) {
      
        // If the element is in st
        // then add it to result array
        if (st.has(b[i])) {
            res.push(b[i]);
        }
    }

    return res;
}

let a = [5, 6, 2, 1, 4];
let b = [7, 9, 4, 2];

let res = intersect(a, b);
console.log(res.join(" "));

Output
4 2 

Time Complexity: O(n + m), where n and m are size of array a[] and b[] respectively.
Auxiliary Space: O(n)

Related Articles:


Next Article
Article Tags :
Practice Tags :

Similar Reads