Open In App

JavaScript Program to Find Union and Intersection of Two Unsorted Arrays

In this article, we will learn how to find the Union and Intersection of two arrays. When an array contains all the elements that are present in both of the arrays, it is called a union. On the other hand, if an array has only those elements that are common in both of the arrays, then it is called an intersection.

Example



Input: 
a = [1,3,5,7,9] , b = [1,2,3,4,6,8,10]

Output:
Union: [1,2,3,4,5,6,7,8,9,10]
Intersection: ans =[1,3]

We will understand the various approaches for finding the union and the intersection of two unsorted Arrays.



Using Set

Union:

Intersection:

Example: This example describes the union & intersection of 2 unsorted Arrays by implementing the Set.




function getIntersection(a, n, b, m) {
    let unionSet = new Set();
    let intersectionSet = new Set();
  
    for (let i = 0; i < n; i++)
        unionSet.add(a[i]);
    console.log("Intersection:");
    for (let i = 0; i < m; i++) {
        if (unionSet.has(b[i])) {
            intersectionSet.add(b[i]);
        }
    }
    let ans = [];
    for (let k of intersectionSet) {
        ans.push(k);
    }
    console.log(ans);
}
function getUnion(a, n, b, m) {
  
    let s = new Set();
  
    // Inserting array elements in s
    for (let i = 0; i < n; i++)
        s.add(a[i]);
  
    for (let i = 0; i < m; i++)
        s.add(b[i]);
    let arr = [];
  
    for (let itr of s)
        arr.push(itr);
    //for sorting     
    arr.sort(function (a, b) { return a - b; })
    console.log("union:");
    console.log(arr);
  
}
  
// Driver Code
  
let a = [1, 2, 5, 6, 2, 3, 5, 7, 3];
let b = [2, 4, 5, 6, 8, 9, 4, 6, 5, 4];
getUnion(a, a.length, b, b.length);
getIntersection(a, a.length, b, b.length);

Output
union:
[
  1, 2, 3, 4, 5,
  6, 7, 8, 9
]
Intersection:
[ 2, 5, 6 ]

Time Complexity: O((n + m) * log(n + m)) for both union and intersection.

Space Complexity: O(n + m) for the union and O(min(n, m)) for the intersection.

Using the map

Union:

Intersection:

Example: This example describes the union & intersection of 2 unsorted Arrays by implementing the Map.




function printUnion(a, n, b, m) {
    let mp = new Map();
  
    // Inserting array elements in mp
    for (let i = 0; i < n; i++) {
        mp.set(a[i], i);
    }
    for (let i = 0; i < m; i++) {
        mp.set(b[i], i);
    }
  
    let ans = [];
    for (let key of mp.keys()) {
        ans.push(key)
    }
    console.log(ans);
}
function getIntersection(a, n, b, m) {
    let mp = new Map();
    let ans = [];
  
    // Inserting elements from array 'a' into the Map
    for (let i = 0; i < n; i++) {
        mp.set(a[i], i);
    }
  
    console.log("Intersection:");
    for (let i = 0; i < m; i++) {
        if (mp.has(b[i])) {
            ans.push(b[i]);
              
            // Map to avoid duplicates in the intersection
            mp.delete(b[i]);
        }
    }
    console.log(ans);
}
  
// Driver Code
  
let a = [1, 2, 5, 6, 2, 3, 5, 7, 3];
let b = [2, 4, 5, 6, 8, 9, 4, 6, 5, 4];
printUnion(a, a.length, b, b.length);
getIntersection(a, a.length, b, b.length);

Output
[
  1, 2, 5, 6,
  3, 4, 8, 9
]
Intersection:
[ 2, 5, 6 ]

Time Complexity: O(m * log(m) + n * log(n))

Auxiliary Space: O(m + n)

Use Sorting

Union:

Intersection:

Example: This example describes the union & intersection of 2 unsorted Arrays by implementing the Sorting.




function printUnion(arr1, arr2, m, n) {
    arr1.sort(function (a, b) { return a - b; });
    arr2.sort(function (a, b) { return a - b; });
    let i = 0;
    let j = 0;
    let ans = [];
    while (i < m && j < n) {
        if (arr1[i] < arr2[j])
            ans.push(arr1[i++]);
        else if (arr2[j] < arr1[i])
            ans.push(arr2[j++]);
  
        else {
            ans.push(arr2[j++]);
            i++;
        }
    }
  
    // Printing remaining elements of the larger array
    while (i < m)
        ans.push(arr1[i++]);
    while (j < n)
        ans.push(arr2[j++]);
    console.log(ans);
}
  
// Function prints intersection of arr1 and arr2
function printIntersection(arr1, arr2, m, n) {
    arr1.sort(function (a, b) { return a - b; });
    arr2.sort(function (a, b) { return a - b; });
    let i = 0;
    let j = 0;
    let ans = [];
    while (i < m && j < n) {
        if (arr1[i] < arr2[j])
            i++;
        else if (arr2[j] < arr1[i])
            j++;
        else {
            ans.push(arr2[j++])
            i++;
        }
    }
    console.log(ans);
}
  
// Driver program to test above function
let arr1 = [7, 1, 5, 2, 3, 6];
let arr2 = [3, 8, 6, 20, 7];
let m = arr1.length;
let n = arr2.length;
  
console.log("Union of two arrays is : ");
printUnion(arr1, arr2, m, n);
  
console.log("Intersection of two arrays is : ");
printIntersection(arr1, arr2, m, n);

Output
Union of two arrays is : 
[
  1, 2, 3,  5,
  6, 7, 8, 20
]
Intersection of two arrays is : 
[ 3, 6, 7 ]

Time complexity: O(mLogm + nLogn)

Space Complexity: O(m + n)

Use Sorting and Searching

Union:

Intersection:

Example: This example describes the union & intersection of 2 unsorted Arrays by implementing Sorting and searching.




function binarySearch(arr, l, r, x) {
    if (r >= l) {
        let mid = l + Math.floor((r - l) / 2);
  
        // If the element is present
        // at the middle itself
        if (arr[mid] == x)
            return mid;
  
        // If element is smaller than mid,
        // then it can only be present 
        // in left subarray
        if (arr[mid] > x)
            return binarySearch(arr, l, mid - 1, x);
  
        // Else right subarray
        return binarySearch(arr, mid + 1, r, x);
    }
  
    // We reach here when element
    // is not present in array
    return -1;
}
  
// Prints union of arr1 and arr2
  
function printUnion(arr1, arr2, m, n) {
  
    // Before finding union, make 
    // sure arr1 is smaller
    if (m > n) {
        let tempp = arr1;
        arr1 = arr2;
        arr2 = tempp;
  
        let temp = m;
        m = n;
        n = temp;
    }
  
  
    let ans = [];
    arr1.sort((a, b) => a - b);
    for (let i = 0; i < m; i++)
        ans.push(arr1[i]);
  
    // Search every element of bigger
    // array in smaller array
    // and print the element if not found
    for (let i = 0; i < n; i++) {
        if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1) { 
            ans.push(arr2[i]); 
        }
    }
    console.log(ans)
}
  
// Prints intersection of arr1 and arr2
  
function printIntersection(arr1, arr2, m, n) {
  
    // Before finding intersection, 
    // make sure arr1[0..m-1] is smaller
    if (m > n) {
        let tempp = arr1;
        arr1 = arr2;
        arr2 = tempp;
  
        let temp = m;
        m = n;
        n = temp;
    }
  
  
    arr1.sort((a, b) => a - b);
  
    // Search every element of bigger array in smaller
    // array and print the element if found
    let ans = [];
    for (let i = 0; i < n; i++) {
        if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1) {
            ans.push(arr2[i]); 
           }
    }
    console.log(ans)
}
  
/* Driver program to test above function */
let arr1 = [7, 1, 5, 2, 3, 6];
let arr2 = [3, 8, 6, 20, 7];
let m = arr1.length;
let n = arr2.length;
  
// Function call
console.log("Union of two arrays is");
printUnion(arr1, arr2, m, n);
  
console.log("Intersection of two arrays is");
printIntersection(arr1, arr2, m, n);

Output
Union of two arrays is
[
   3, 6, 7, 8,
  20, 1, 5, 2
]
Intersection of two arrays is
[ 7, 3, 6 ]

Time Complexity: O(max(m*log(m), n*log(n)) + min(m, n) )

Auxiliary Space: O(1)

Without using hashing or any predefined library like sets or maps and works even for both repeated and distant elements

First of all, we sort both arrays and proceed as below:

Union

Intersection

Example: This example describes the union & intersection of 2 unsorted Arrays.




// Function to find union
function Union(a, b, n, m) {
  
    let result = new Array(n + m);
  
    let index = 0;
    let left = 0, right = 0;
    while (left < n && right < m) {
  
        if (a[left] < b[right]) {
            if (index != 0
                && a[left] == result[index - 1]) {
                left++;
            }
            else {
                result[index] = a[left];
                left++;
                index++;
            }
        }
        else {
            if (index != 0
                && b[right] == result[index - 1]) {
                right++;
            }
            else {
                result[index] = b[right];
                right++;
                index++;
            }
        }
    }
  
    while (left < n) {
        if (index != 0 && a[left] == result[index - 1]) {
            left++;
        }
        else {
            result[index] = a[left];
            left++;
            index++;
        }
    }
  
    while (right < m) {
        if (index != 0 && b[right] == result[index - 1]) {
            right++;
        }
        else {
            result[index] = b[right];
            right++;
            index++;
        }
    }
    let ans = [];
  
    console.log("Union: ");
    for (let k = 0; k < index; k++) { ans.push(result[k]); }
    console.log(ans)
  
}
  
// Function to find intersection
function intersection(a, b, n, m) {
  
    let i = 0, j = 0, k = 0;
    let result = new Array(n + m);
    while (i < n && j < m) {
        if (a[i] < b[j])
            i++;
        else if (a[i] > b[j])
            j++;
        else {
            if (k != 0 && a[i] == result[k - 1]) {
                i++;
                j++;
            }
            else {
                result[k] = a[i];
                i++;
                j++;
                k++;
            }
        }
    }
    let ans = [];
    console.log("Intersection: ");
    for (let x = 0; x < k; x++) { ans.push(result[x]); }
    console.log(ans)
}
  
// Driver Code
let a = [1, 3, 2, 3, 3, 4, 5, 5, 6];
let b = [3, 3, 5];
  
let n = a.length;
let m = b.length;
  
// sort
a.sort();
b.sort();
  
// Function call
Union(a, b, n, m);
intersection(a, b, n, m);

Output
Union: 
[ 1, 2, 3, 4, 5, 6 ]
Intersection: 
[ 3, 5 ]

Kind of hashing technique without using any predefined JavaScript Collections

Example: This example describes the union & intersection of 2 unsorted Arrays.




function printUnion(arr1, arr2, n1, n2) {
    // Defining set container s
    let s = new Set();
  
    // Insert the elements of arr1[] to set s
    for (let i = 0; i < n1; i++) {
        s.add(arr1[i]);
    }
  
    // Insert the elements of arr2[] to set s
    for (let i = 0; i < n2; i++) {
        s.add(arr2[i]);
    }
    let ans = [];
    console.log("Union:");
    for (let itr of s)
      
        // s will contain only distinct
        // elements from array a and b
        ans.push(itr);
  
    console.log(ans);
    // Prints intersection of arr1[0..n1-1] and
    // arr2[0..n2-1]
}
  
function printIntersection(arr1, arr2, n1, n2) {
  
    // Defining set container s
    let s = new Set();
    let ans = [];
  
    // Insert the elements of arr1[] to set s
    for (let i = 0; i < n1; i++) {
        s.add(arr1[i]);
    }
  
    console.log("Intersection:");
  
    for (let i = 0; i < n2; i++) {
  
        // If element is present in set then
        if (s.has(arr2[i])) {
            ans.push(arr2[i]);
        }
    }
  
    console.log(ans);
}
  
// Driver Code
let arr1 = [7, 1, 5, 2, 3, 6];
let arr2 = [3, 8, 6, 20, 7];
let n1 = arr1.length;
let n2 = arr2.length;
  
printUnion(arr1, arr2, n1, n2);
printIntersection(arr1, arr2, n1, n2);

Output
Union:
[
  7, 1, 5,  2,
  3, 6, 8, 20
]
Intersection:
[ 3, 6, 7 ]

Time complexity: for union is O(n1 + n2), and for intersection is O(n1 + n2).

Space complexity: for union is O(n1 + n2), and for intersection is O(min(n1, n2)).


Article Tags :