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)).
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]
Table of Content
- Using Set
- Using the map
- Use Sorting
- Use Sorting and Searching
- Without using hashing or any predefined library like sets or maps and works even for both repeated and distant elements
- Kind of hashing technique without using any predefined JavaScript Collections
We will understand the various approaches for finding the union and the intersection of two unsorted Arrays.