Open In App

JavaScript Program to Find Union and Intersection of Two Unsorted Arrays

Last Updated : 26 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Creating functions and passing both arrays and their respective lengths.
  • Initializing a set as a union set.
  • Iterating both of the arrays and storing elements in the set.
  • After sorting the printing elements of the set.

Intersection:

  • Creating a function and passing both arrays and their respective lengths.
  • Initializing 2 sets one for storing union and another for storing intersection.
  • Iterating the array and checking if that value is already present in the union set.
  • We will add those elements of the array which are already present in the union set.
  • Creating an array and storing the value of the intersection set into it and printing the array.

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

Javascript




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:

  • Creating functions and passing both arrays and their respective lengths.
  • Initializing a map mp and storing the element’s key value pairwise.
  • Iterating mp and storing unique value using mp.keys() function into an array.
  • Printing array in the console.

Intersection:

  • Creating functions and passing both arrays and their respective lengths.
  • Initializing a map mp and storing the elements of the first array in key-value pairwise
  • Iterating the second array and checking for the presence of each element in the mp map, If that element is present in mp then we will add that element into the intersection array.
  • And will delete that element from mp for the avoidance of duplicates in the intersection array.

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

Javascript




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:

  • The first step is to sort both arrays.
  • Now, use the two-pointer approach, if the current element is smaller then store it in ans.
  • Else, if elements are equal then simply store either the first array element or the second array.

Intersection:

  • The first step is to sort both arrays.
  • Now, use the two-pointer approach, if the current element is smaller then increment the first array otherwise increment the second array.
  • If elements are equal then simply store the element in the ans array.

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

Javascript




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:

  • Sort the smaller array, arr1, in ascending order.
  • Initialize an empty array ans to store the union.
  • Iterate through arr1 and add its elements to the ans array. For each element in arr2, check if it’s already in the ans array using binary search. If not found, add it to the ans array.

Intersection:

  • Determine the smaller array between arr1 and arr2. If arr1 is larger, swap them.
  • Sort the smaller array, arr1, in ascending order.
  • Initialize an empty array ans to store the intersection.
  • Iterate through arr1 and use binary search to check if each element exists in the larger array, arr2. If found in both arrays, add it to the ans array.

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

Javascript




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

  • Iterate in a while loop until any one array is finished.
  • In each iteration, we look for smaller in both arrays and we print it and increment its pointer only if it is not the same as the last element printed in union.
  • After we finish, while loop iterate the remaining two arrays in a similar way as above and print the union.

Intersection

  • Iterate in a while loop till any of the one array is finished.
  • In each iteration, we look for the smaller of the two elements from both the array and increase its pointer because it will not be in the other list, hence not part of the intersection.
  • For an intersection, if both the elements are equal we print it and increment both pointers only if it is not the same as the last element printed in an intersection.

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

Javascript




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

  • Initialize the array with a size of m+n
  • Fill the first array value in a resultant array by doing hashing(to find the appropriate position).
  • Repeat for the second array.
  • While doing hashing if a collision happens increment the position in a recursive way.

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

Javascript




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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads