Skip to content
Related Articles

Related Articles

Find Union and Intersection of two unsorted arrays

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 01 Jul, 2022

Given two unsorted arrays that represent two sets (elements in every array are distinct), find the union and intersection of two arrays.

For example, if the input arrays are: 

arr1[] = {7, 1, 5, 2, 3, 6} 
arr2[] = {3, 8, 6, 20, 7} 

Then your program should print Union as {1, 2, 3, 5, 6, 7, 8, 20} and Intersection as {3, 6, 7}. Note that the elements of union and intersection can be printed in any order.

Complete Interview Preparation - GFG

Method 1 (Using Set):

Union of two arrays we can get with the Set data structure very easily. Set is a data structure that allows only the distinct elements in it. So, when we put the elements of both the array into the set we will get only the distinct elements that are equal to the union operation over the arrays. Let’s code it now –> 

C++




// C++ program for the union of two arrays using Set
#include <bits/stdc++.h>
using namespace std;
void getUnion(int a[], int n, int b[], int m)
{
      
    // Defining set container s
    set<int> s; 
    
    // Inserting array elements in s
    for (int i = 0; i < n; i++) 
      s.insert(a[i]);
    
    for (int i = 0; i < m; i++)
        s.insert(b[i]);
    cout << "Number of elements after union operation: " << s.size() << endl;
      cout << "The union set of both arrays is :" << endl;
    for (auto itr = s.begin(); itr != s.end(); itr++)
        cout << *itr
             << " "; // s will contain only distinct
                     // elements from array a and b
}
  
// Driver Code
int main()
{
    int a[9] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; 
    int b[10] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; 
  
    getUnion(a, 9, b, 10); 
}
  
// contributed by Anirban Chand

Java




// Java program for the union of two arrays using Set
import java.util.*;
  
class GFG{
static void getUnion(int a[], int n, int b[], int m)
{
      
    // Defining set container s
    HashSet<Integer> s = new HashSet<>(); 
    
    // Inserting array elements in s
    for (int i = 0; i < n; i++) 
      s.add(a[i]);
    
    for (int i = 0; i < m; i++)
        s.add(b[i]);
    System.out.print("Number of elements after union operation: " +  s.size() +"\n");
      System.out.print("The union set of both arrays is :" +"\n");
      
        System.out.print(s.toString()+ " "); // s will contain only distinct
                     // elements from array a and b
}
  
// Driver Code
public static void main(String[] args)
{
    int a[] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; 
    int b[] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; 
  
    getUnion(a, 9, b, 10); 
}
}
  
// This code is contributed by gauravrajput1 

Python3




# Python program for the union of two arrays using Set
def getUnion(a, n, b, m):
  
    # Defining set container s
    s =set();
  
    # Inserting array elements in s
    for i in range(n):
        s.add(a[i]);
  
    for i in range(m):
        s.add(b[i]);
    print("Number of elements after union operation: " , len(s) , "");
    print("The union set of both arrays is :" + "");
  
    print(s, end=""); # s will contain only distinct
    # elements from array a and b
  
# Driver Code
if __name__ == '__main__':
    a = [ 1, 2, 5, 6, 2, 3, 5, 7, 3 ];
    b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 ];
  
    getUnion(a, 9, b, 10);
  
# This code is contributed by gauravrajput1 

C#




// C# program for the union of two arrays using Set
using System;
using System.Collections.Generic;
  
public class GFG {
    static void getUnion(int []a, int n, int []b, int m) {
  
        // Defining set container s
        HashSet<int> s = new HashSet<int>();
  
        // Inserting array elements in s
        for (int i = 0; i < n; i++)
            s.Add(a[i]);
  
        for (int i = 0; i < m; i++)
            s.Add(b[i]);
        Console.Write("Number of elements after union operation: " + s.Count + "\n");
        Console.Write("The union set of both arrays is :" + "\n");
        foreach(int i in s)
        Console.Write(i + " "); // s will contain only distinct
        // elements from array a and b
    }
  
    // Driver Code
    public static void Main(String[] args) {
        int []a = { 1, 2, 5, 6, 2, 3, 5, 7, 3 };
        int []b = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 };
  
        getUnion(a, 9, b, 10);
    }
}
  
// This code is contributed by umadevi9616

Javascript




<script>
  
       // JavaScript program for the above
       // approach using Set
 
       function getUnion(a, n, b, m) {
 
           // Defining set container s
           var 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]);
           document.write(
           "Number of elements after union operation: " 
           + s.size + "<br>");
           document.write("The union set of both arrays is :");
           document.write("<br>");
           var arr = [];
           for (let itr of s)
               arr.push(itr);
           // s will contain only distinct
           // elements from array a and b
           arr.sort(function (a, b) { return a - b; })
           for (let i = 0; i < arr.length; i++) {
               document.write(arr[i] + " ");
           }
       }
 
       // 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, 9, b, 10);
 
    // This code is contributed by Potta Lokesh
 
 
   </script>

Output

Number of elements after union operation: 9
The union set of both arrays is :
1 2 3 4 5 6 7 8 9 

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

Note: O(m + n) in case of Python because in python the set built-in method is quite different than that of C++ once, Python uses an hash map internally.

We can improve performance of getUnion method by iterating over both the arrays for index from 0 to min(n, m)-1 adding all the elements in both the arrays to the set, and then iterate over the other array with the remaining elements and add them to the set.

C++




// C++ program for the union of two arrays using Set
#include <bits/stdc++.h>
using namespace std;
void getUnion(int a[], int n, int b[], int m)
{
    int min=(n<m)? n : m;
       
    // Defining set container s
    set<int> s;
     
    // add elements from both the arrays for
    // index from 0 to min(n, m)-1
    for (int i = 0; i < min; i++)
    {
      s.insert(a[i]);
      s.insert(b[i]);
    }
      
    if (n > m) 
    {
        for (int i = m; i < n; i++) 
        {
            s.insert(a[i]);
        }
    }
    else if (n < m) 
    {
        for (int i = n; i < m; i++) 
        {
            s.insert(b[i]);
        }
    }
      
    cout << "Number of elements after union operation: " << s.size() << endl;
      cout << "The union set of both arrays is :" << endl;
    for (auto itr = s.begin(); itr != s.end(); itr++)
        cout << *itr
             << " "; // s will contain only distinct
                     // elements from array a and b
}
   
// Driver Code
int main()
{
    int a[9] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 };
    int b[10] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 };
   
    getUnion(a, 9, b, 10);
}
  
// This code is contributed by Aarti_Rathi

Java




// Java program for the union of two arrays using Set
import java.util.*;
  
class GFG {
    static void getUnion(int a[], int n, int b[], int m)
    {
        // find min of n and m
        int min = (n < m) ? n : m;
  
        // set container
        Set<Integer> set = new HashSet<>();
  
        // add elements from both the arrays for
        // index from 0 to min(n, m)-1
        for (int i = 0; i < min; i++) {
            set.add(a[i]);
            set.add(b[i]);
        }
  
        // add remiaining elements to the set from the other
        // array (having greater length)
        // note that only one of the loops will execute
        if (n > m) {
            for (int i = m; i < n; i++) {
                set.add(a[i]);
            }
        }
        else if (n < m) {
            for (int i = n; i < m; i++) {
                set.add(b[i]);
            }
        }
  
        // driver code to print the output
        System.out.println("Number of elements after union operation: " + set.size());
        System.out.println("The union set of both arrays is :");
        System.out.print(set.toString());
    }
    // Driver Code
    public static void main(String[] args)
    {
        int a[] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 };
        int b[] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 };
  
        getUnion(a, 9, b, 10);
    }
}
  
// This code is contributed by Parth Malhotra

Python3




# Python program for the union of two arrays using Set
def getUnion(a, n, b, m):
    
    # Defining set container s
    hs = set()
    if(n<m):
        min=n
    else:
        min=m
          
    # add elements from both the arrays for
    # index from 0 to min(n, m)-1
    for i in range(0, min):
        hs.add(a[i])
        hs.add(b[i])
      
    if(n>m):
        for i in range(m, n):
            hs.add(a[i])
    else:
        if(n<m):
            for i in range(m, n):
                hs.add(b[i])
              
              
    print("Number of elements after union operation: ",len(hs))
    print("The union set of both arrays is :")
    for i in hs:
        print(i, end=" ")
    print("\n")
    # s will contain only distinct
    # elements from array a and b
  
# Driver Program
a = [1, 2, 5, 6, 2, 3, 5, 7, 3]
b = [2, 4, 5, 6, 8, 9, 4, 6, 5, 4]
n1 = len(a)
n2 = len(b)
  
# Function call
getUnion(a, n1, b, n2)
  
# This code is contributed by Aarti_Rathi

C#




// C# program for the union of two arrays using Set
using System;
using System.Collections.Generic;
  
public class GFG {
  static void getUnion(int []a, int n, int []b, int m) 
  {
  
    // find min of n and m
    int min = (n < m) ? n : m;
  
    // set container
    HashSet<int> set = new HashSet<int>();
  
    // add elements from both the arrays for
    // index from 0 to min(n, m)-1
    for (int i = 0; i < min; i++) {
      set.Add(a[i]);
      set.Add(b[i]);
    }
  
    // add remiaining elements to the set from the other
    // array (having greater length)
    // note that only one of the loops will execute
    if (n > m) {
      for (int i = m; i < n; i++) {
        set.Add(a[i]);
      }
    } else if (n < m) {
      for (int i = n; i < m; i++) {
        set.Add(b[i]);
      }
    }
  
    // driver code to print the output
    Console.WriteLine("Number of elements after union operation: " + set.Count);
    Console.WriteLine("The union set of both arrays is :[");
    foreach(int x in set)
      Console.Write(x+", ");
    Console.Write("]");
  }
  
  // Driver Code
  public static void Main(String[] args) {
    int []a = { 1, 2, 5, 6, 2, 3, 5, 7, 3 };
    int []b = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 };
  
    getUnion(a, 9, b, 10);
  }
}
  
// This code is contributed by Rajput-Ji 

Javascript




<script>
// javascript program for the union of two arrays using Set
    function getUnion(a , n , b , m) {
        // find min of n and m
        var min = (n < m) ? n : m;
  
        // set container
        var set = new Set();
  
        // add elements from both the arrays for
        // index from 0 to min(n, m)-1
        for (i = 0; i < min; i++) {
            set.add(a[i]);
            set.add(b[i]);
        }
  
        // add remiaining elements to the set from the other
        // array (having greater length)
        // note that only one of the loops will execute
        if (n > m) {
            for (i = m; i < n; i++) {
                set.add(a[i]);
            }
        } else if (n < m) {
            for (i = n; i < m; i++) {
                set.add(b[i]);
            }
        }
  
        // driver code to print the output
        document.write("Number of elements after union operation: " + set.size);
        document.write("<br/>The union set of both arrays is :<br/>");
        set.forEach (function(value) {
document.write(value+" ");
})
          
    }
  
    // Driver Code
      
        var a = [ 1, 2, 5, 6, 2, 3, 5, 7, 3 ];
        var b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 ];
  
        getUnion(a, 9, b, 10);
// This code contributed by Rajput-Ji 
</script>

Output

Number of elements after union operation: 9
The union set of both arrays is :
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Time Complexity: O( max(m,n) )

Method 2: (Using map data structure)

From the knowledge of data structures, we know that map stores distinct keys only. So if we insert any key appearing more than one time it gets stored only once. The idea is to insert both the arrays in one common map which would then store the distinct elements of both arrays (union of both the array).

Below is the implementation of the above method:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
void printUnion(int* a, int n, int* b, int m)
{
      
    // Defining map container mp
    map<int, int> mp; 
    
    // Inserting array elements in mp
    for (int i = 0; i < n; i++)
        mp.insert({ a[i], i }); 
    
    for (int i = 0; i < m; i++)
        mp.insert({ b[i], i });
    cout << "The union set of both arrays is :" << endl;
    for (auto itr = mp.begin(); itr != mp.end(); itr++)
        cout << itr->first
             << " "; // mp will contain only distinct
                     // elements from array a and b
}
  
// Driver Code
int main()
{
    int a[7] = { 1, 2, 5, 6, 2, 3, 5 }; 
    int b[9] = { 2, 4, 5, 6, 8, 9, 4, 6, 5 }; 
  
    printUnion(a, 7, b, 9); 
}

Java




// Java program for the above approach
import java.io.*;
import java.util.*;
  
class GFG{
  
static void printUnion(int[] a, int n, 
                       int[] b, int m)
{
    Map<Integer, 
        Integer> mp = new HashMap<Integer,
                                  Integer>(); 
      
    // Inserting array elements in mp
    for(int i = 0; i < n; i++)
    {
        mp.put(a[i], i);
    }
    for(int i = 0; i < m; i++)
    {
        mp.put(b[i], i);
    }
      
    System.out.println("The union set of both arrays is :");
    for(Map.Entry mapElement : mp.entrySet())
    {
        System.out.print(mapElement.getKey() + " ");
          
        // mp will contain only distinct
        // elements from array a and b
    }
}
  
// Driver Code
public static void main (String[] args) 
{
    int a[] = { 1, 2, 5, 6, 2, 3, 5 }; 
    int b[] = { 2, 4, 5, 6, 8, 9, 4, 6, 5 }; 
      
    printUnion(a, 7, b, 9);
}
}
  
// This code is contributed by avanitrachhadiya2155

Python3




# Python program for the above approach
def printUnion(a , n,  b , m):
    mp = {}
      
    # Inserting array elements in mp
    for i in range(n):
        mp[a[i]] = i
  
    for i in range(m):
        mp[b[i]] = i
      
    print("The union set of both arrays is : ");
    for key in mp.keys():
  
        print(key,end=" ")
  
# Driver Code
a = [ 1, 2, 5, 6, 2, 3, 5 ]; 
b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5 ]; 
      
printUnion(a, 7, b, 9)
  
# This code is contributed by shinjanpatra

C#




// C# program for the above approach
  
using System;
using System.Collections.Generic;
  
public class GFG{
  
static void printUnion(int[] a, int n, 
                       int[] b, int m)
{
    Dictionary<int
        int> mp = new Dictionary<int,
                                  int>(); 
      
    // Inserting array elements in mp
    for(int i = 0; i < n; i++)
    {
        if(!mp.ContainsKey(a[i]))
        mp.Add(a[i], i);
    }
    for(int i = 0; i < m; i++)
    {
        if(!mp.ContainsKey(b[i]))
        mp.Add(b[i], i);
    }
      
    Console.WriteLine("The union set of both arrays is :");
    foreach(KeyValuePair<int,int> mapElement in mp)
    {
        Console.Write(mapElement.Key + " ");
          
        // mp will contain only distinct
        // elements from array a and b
    }
}
  
// Driver Code
public static void Main(String[] args) 
{
    int []a = { 1, 2, 5, 6, 2, 3, 5 }; 
    int []b = { 2, 4, 5, 6, 8, 9, 4, 6, 5 }; 
      
    printUnion(a, 7, b, 9);
}
}
  
// This code contributed by gauravrajput1

Javascript




<script>
// javascript program for the above approach
function printUnion(a , n,  b , m)
{
    var mp = new Map(); 
      
    // Inserting array elements in mp
    for(var i = 0; i < n; i++)
    {
        mp.set(a[i], i);
    }
    for(var i = 0; i < m; i++)
    {
        mp.set(b[i], i);
    }
      
    document.write("The union set of both arrays is :<br/>");
    for(var key of mp.keys())
    {
        document.write(key + " ");
  
    }
}
  
// Driver Code
    var a = [ 1, 2, 5, 6, 2, 3, 5 ]; 
    var b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5 ]; 
      
    printUnion(a, 7, b, 9);
  
// This code is contributed by gauravrajput1
</script>

Output

The union set of both arrays is :
1 2 3 4 5 6 8 9 

The above method has time complexity O(m+n).

*This method is suggested by Vinay Verma

Method 3 (Naive) 

Union: 

  1. Initialize union U as empty.
  2. Copy all elements of the first array to U.
  3. Do the following for every element x of the second array:
    1. If x is not present in the first array, then copy x to U.
  4. Return U.

Intersection: 

  1. Initialize intersection I as empty.
  2. Do the following for every element x of the first array
    1. If x is present in the second array, then copy x to I.
  3. Return I.

The time complexity of this method is O(mn) for both operations. Here m and n are numbers of elements in arr1[] and arr2[] respectively.

However, above method works only for distinct elements in input arrays.

Method 4 (Use Sorting) 

  1. Sort arr1[] and arr2[]. This step takes O(mLogm + nLogn) time.
  2. Use O(m + n) algorithms to find the union and intersection of two sorted arrays.

The overall time complexity of this method is O(mLogm + nLogn).

Method 5 (Use Sorting and Searching) 
Union: 

  1. Initialize union U as empty.
  2. Find smaller m and n and sort the smaller array.
  3. Copy the smaller array to U.
  4. For every element x of a larger array, do the following
    1. Binary Search x in the smaller array. If, x is not present, then copy it to U.
  5. Return U.

Intersection: 

  1. Initialize intersection I as empty.
  2. Find smaller of m and n and sort the smaller array.
  3. For every element x of a larger array, do the following
    1. Binary Search x in the smaller array. If x is present, then copy it to I.
  4. Return I.

Time complexity of this method is min(mLogm + nLogm, mLogn + nLogn) which can also be written as O((m+n)Logm, (m+n)Logn). This approach works much better than the previous approach when the difference between the sizes of two arrays is significant.
Thanks to use_the_force for suggesting this method in a comment here

Below is the implementation of this method. However, this method also works only for distinct elements in input arrays.

C++




// A C++ program to print union and intersection
/// of two unsorted arrays
#include <algorithm>
#include <iostream>
using namespace std;
  
int binarySearch(int arr[], int l, int r, int x);
  
// Prints union of arr1[0..m-1] and arr2[0..n-1]
void printUnion(int arr1[], int arr2[], int m, int n)
{
    // Before finding union, make sure arr1[0..m-1]
    // is smaller
    if (m > n) {
        int* tempp = arr1;
        arr1 = arr2;
        arr2 = tempp;
  
        int temp = m;
        m = n;
        n = temp;
    }
  
    // Now arr1[] is smaller
  
    // Sort the first array and print its elements (these
    // two steps can be swapped as order in output is not
    // important)
    sort(arr1, arr1 + m);
    for (int i = 0; i < m; i++)
        cout << arr1[i] << " ";
  
    // Search every element of bigger array in smaller array
    // and print the element if not found
    for (int i = 0; i < n; i++)
        if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1)
            cout << arr2[i] << " ";
}
  
// Prints intersection of arr1[0..m-1] and arr2[0..n-1]
void printIntersection(int arr1[], int arr2[], int m, int n)
{
    // Before finding intersection, make sure arr1[0..m-1]
    // is smaller
    if (m > n) {
        int* tempp = arr1;
        arr1 = arr2;
        arr2 = tempp;
  
        int temp = m;
        m = n;
        n = temp;
    }
  
    // Now arr1[] is smaller
  
    // Sort smaller array arr1[0..m-1]
    sort(arr1, arr1 + m);
  
    // Search every element of bigger array in smaller
    // array and print the element if found
    for (int i = 0; i < n; i++)
        if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1)
            cout << arr2[i] << " ";
}
  
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
    if (r >= l) {
        int mid = l + (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 the element can only be present in right
        // subarray
        return binarySearch(arr, mid + 1, r, x);
    }
  
    // We reach here when element is not present in array
    return -1;
}
  
/* Driver program to test above function */
int main()
{
    int arr1[] = { 7, 1, 5, 2, 3, 6 };
    int arr2[] = { 3, 8, 6, 20, 7 };
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
    
    // Function call
    cout << "Union of two arrays is n";
    printUnion(arr1, arr2, m, n);
    cout << "nIntersection of two arrays is n";
    printIntersection(arr1, arr2, m, n);
    return 0;
}

Java




// A Java program to print union and intersection
/// of two unsorted arrays
import java.util.Arrays;
  
class UnionAndIntersection {
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    void printUnion(int arr1[], int arr2[], int m, int n)
    {
        // Before finding union, make sure arr1[0..m-1]
        // is smaller
        if (m > n) {
            int tempp[] = arr1;
            arr1 = arr2;
            arr2 = tempp;
  
            int temp = m;
            m = n;
            n = temp;
        }
  
        // Now arr1[] is smaller
        // Sort the first array and print its elements
        // (these two steps can be swapped as order in
        // output is not important)
        Arrays.sort(arr1);
        for (int i = 0; i < m; i++)
            System.out.print(arr1[i] + " ");
  
        // Search every element of bigger array in smaller
        // array and print the element if not found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1)
                System.out.print(arr2[i] + " ");
        }
    }
  
    // Prints intersection of arr1[0..m-1] and arr2[0..n-1]
    void printIntersection(int arr1[], int arr2[], int m,
                           int n)
    {
        // Before finding intersection, make sure
        // arr1[0..m-1] is smaller
        if (m > n) {
            int tempp[] = arr1;
            arr1 = arr2;
            arr2 = tempp;
  
            int temp = m;
            m = n;
            n = temp;
        }
  
        // Now arr1[] is smaller
        // Sort smaller array arr1[0..m-1]
        Arrays.sort(arr1);
  
        // Search every element of bigger array in smaller
        // array and print the element if found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1)
                System.out.print(arr2[i] + " ");
        }
    }
  
    // A recursive binary search function. It returns
    // location of x in given array arr[l..r] is present,
    // otherwise -1
    int binarySearch(int arr[], int l, int r, int x)
    {
        if (r >= l) {
            int mid = l + (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 the element can only be present in right
            // subarray
            return binarySearch(arr, mid + 1, r, x);
        }
  
        // We reach here when element is not present in
        // array
        return -1;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        UnionAndIntersection u_i
            = new UnionAndIntersection();
        int arr1[] = { 7, 1, 5, 2, 3, 6 };
        int arr2[] = { 3, 8, 6, 20, 7 };
        int m = arr1.length;
        int n = arr2.length;
        
        // Function call
        System.out.println("Union of two arrays is ");
        u_i.printUnion(arr1, arr2, m, n);
        System.out.println("");
        System.out.println(
            "Intersection of two arrays is ");
        u_i.printIntersection(arr1, arr2, m, n);
    }
}

Python3




# A Python3 program to print union and intersection
# of two unsorted arrays
  
# Prints union of arr1[0..m-1] and arr2[0..n-1]
  
  
def printUnion(arr1, arr2, m, n):
  
    # Before finding union, make sure arr1[0..m-1]
    # is smaller
    if (m > n):
        tempp = arr1
        arr1 = arr2
        arr2 = tempp
  
        temp = m
        m = n
        n = temp
  
    # Now arr1[] is smaller
  
    # Sort the first array and print its elements (these two
    # steps can be swapped as order in output is not important)
    arr1.sort()
    for i in range(0, m):
        print(arr1[i], end=" ")
  
    # Search every element of bigger array in smaller array
    # and print the element if not found
    for i in range(0, n):
        if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1):
            print(arr2[i], end=" ")
  
# Prints intersection of arr1[0..m-1] and arr2[0..n-1]
  
  
def printIntersection(arr1, arr2, m, n):
  
    # Before finding intersection, make sure arr1[0..m-1]
    # is smaller
    if (m > n):
        tempp = arr1
        arr1 = arr2
        arr2 = tempp
  
        temp = m
        m = n
        n = temp
  
    # Now arr1[] is smaller
  
    # Sort smaller array arr1[0..m-1]
    arr1.sort()
  
    # Search every element of bigger array in smaller
    # array and print the element if found
    for i in range(0, n):
        if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1):
            print(arr2[i], end=" ")
  
# A recursive binary search function. It returns
# location of x in given array arr[l..r] is present,
# otherwise -1
  
  
def binarySearch(arr, l, r, x):
  
    if (r >= l):
        mid = int(l + (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 the element can only be present in right subarray
        return binarySearch(arr, mid + 1, r, x)
  
    # We reach here when element is not present in array
    return -1
  
  
# Driver code
arr1 = [7, 1, 5, 2, 3, 6]
arr2 = [3, 8, 6, 20, 7]
m = len(arr1)
n = len(arr2)
  
# Function call
print("Union of two arrays is ")
printUnion(arr1, arr2, m, n)
print("\nIntersection of two arrays is ")
printIntersection(arr1, arr2, m, n)
  
# This code is contributed by mits

C#




// A C# program to print union and
// intersection of two unsorted arrays
using System;
  
class GFG {
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    static void printUnion(int[] arr1, int[] arr2, int m,
                           int n)
    {
        // Before finding union, make
        // sure arr1[0..m-1] is smaller
        if (m > n) {
            int[] tempp = arr1;
            arr1 = arr2;
            arr2 = tempp;
  
            int temp = m;
            m = n;
            n = temp;
        }
  
        // Now arr1[] is smaller
        // Sort the first array and print
        // its elements (these two steps can
        // be swapped as order in output is
        // not important)
        Array.Sort(arr1);
        for (int i = 0; i < m; i++)
            Console.Write(arr1[i] + " ");
  
        // Search every element of bigger
        // array in smaller array and print
        // the element if not found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1)
                Console.Write(arr2[i] + " ");
        }
    }
  
    // Prints intersection of arr1[0..m-1]
    // and arr2[0..n-1]
    static void printIntersection(int[] arr1, int[] arr2,
                                  int m, int n)
    {
        // Before finding intersection,
        // make sure arr1[0..m-1] is smaller
        if (m > n) {
            int[] tempp = arr1;
            arr1 = arr2;
            arr2 = tempp;
  
            int temp = m;
            m = n;
            n = temp;
        }
  
        // Now arr1[] is smaller
        // Sort smaller array arr1[0..m-1]
        Array.Sort(arr1);
  
        // Search every element of bigger array in
        // smaller array and print the element if found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1)
                Console.Write(arr2[i] + " ");
        }
    }
  
    // A recursive binary search function.
    // It returns location of x in given
    // array arr[l..r] is present, otherwise -1
    static int binarySearch(int[] arr, int l, int r, int x)
    {
        if (r >= l) {
            int mid = l + (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 the element can only be
            // present in right subarray
            return binarySearch(arr, mid + 1, r, x);
        }
  
        // We reach here when element is
        // not present in array
        return -1;
    }
  
    // Driver Code
    static public void Main()
    {
        int[] arr1 = { 7, 1, 5, 2, 3, 6 };
        int[] arr2 = { 3, 8, 6, 20, 7 };
        int m = arr1.Length;
        int n = arr2.Length;
        
        // Function call
        Console.WriteLine("Union of two arrays is ");
        printUnion(arr1, arr2, m, n);
        Console.WriteLine("");
        Console.WriteLine("Intersection of two arrays is ");
        printIntersection(arr1, arr2, m, n);
    }
}
  
// This code is contributed
// by Sach_Code

PHP




<?php
// A PHP program to print union and intersection 
/// of two unsorted arrays
  
// Prints union of arr1[0..m-1] and arr2[0..n-1]
function printUnion($arr1, $arr2, $m, $n)
{
    // Before finding union, make sure arr1[0..m-1] 
    // is smaller
    if ($m > $n)
    {
        $tempp = $arr1;
        $arr1 = $arr2;
        $arr2 = $tempp;
  
        $temp = $m;
        $m = $n;
        $n = $temp;
    }
  
    // Now arr1[] is smaller
  
    // Sort the first array and print its elements (these two
    // steps can be swapped as order in output is not important)
    sort($arr1);
    for ($i = 0; $i < $m; $i++)
        echo $arr1[$i]." ";
  
    // Search every element of bigger array in smaller array
    // and print the element if not found
    for ($i = 0; $i < $n; $i++)
        if (binarySearch($arr1, 0, $m - 1, $arr2[$i]) == -1)
            echo $arr2[$i]." ";
}
  
// Prints intersection of arr1[0..m-1] and arr2[0..n-1]
function printIntersection($arr1, $arr2, $m, $n)
{
    // Before finding intersection, make sure arr1[0..m-1] 
    // is smaller
    if ($m > $n)
    {
        $tempp = $arr1;
        $arr1 = $arr2;
        $arr2 = $tempp;
  
        $temp = $m;
        $m = $n;
        $n = $temp;
    }
  
    // Now arr1[] is smaller
  
    // Sort smaller array arr1[0..m-1]
    sort($arr1);
  
    // Search every element of bigger array in smaller
    // array and print the element if found
    for ($i = 0; $i < $n; $i++)
        if (binarySearch($arr1, 0, $m - 1, $arr2[$i]) != -1)
            echo $arr2[$i]." ";
}
  
// A recursive binary search function. It returns 
// location of x in given array arr[l..r] is present, 
// otherwise -1
function binarySearch($arr, $l, $r,$x)
{
    if ($r >= $l)
    {
        $mid = (int)($l + ($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 the element can only be present in right subarray
        return binarySearch($arr, $mid + 1, $r, $x);
    }
  
    // We reach here when element is not present in array
    return -1;
}
  
/* Driver program to test above function */
    $arr1 = array(7, 1, 5, 2, 3, 6);
    $arr2 = array(3, 8, 6, 20, 7);
    $m = count($arr1);
    $n = count($arr2);
    echo "Union of two arrays is \n";
    printUnion($arr1, $arr2, $m, $n);
    echo "\nIntersection of two arrays is \n";
    printIntersection($arr1, $arr2, $m, $n);
  
// This code is contributed by mits
?>

Javascript




<script>
  
// A JavaScript program to 
// print union and intersection
// of two unsorted arrays
  
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
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 the element can only be present in 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[0..m-1] and arr2[0..n-1]
function printUnion(arr1, arr2, m, n)
{
    // Before finding union, 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;
    }
  
    // Now arr1[] is smaller
  
    // Sort the first array and print its elements (these
    // two steps can be swapped as order in output is not
    // important)
    arr1.sort((a, b) => a - b);
    for (let i = 0; i < m; i++)
        document.write(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)
            document.write(arr2[i] + " ");
}
  
// Prints intersection of arr1[0..m-1] and arr2[0..n-1]
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;
    }
  
    // Now arr1[] is smaller
  
    // Sort smaller array arr1[0..m-1]
    arr1.sort((a, b) => a - b);
  
    // Search every element of bigger array in smaller
    // array and print the element if found
    for (let i = 0; i < n; i++)
        if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1)
            document.write(arr2[i] + " ");
}
  
  
  
/* 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
    document.write("Union of two arrays is <br>");
    printUnion(arr1, arr2, m, n);
    document.write("<br>Intersection of two arrays is<br>");
    printIntersection(arr1, arr2, m, n);
  
// This code is contributed by Surbhi Tyagi.
</script>

Output

Union of two arrays is n3 6 7 8 20 1 5 2 nIntersection of two arrays is n7 3 6 

Another Approach (When elements in the array may not be distinct) :

C++




// C++ code to find intersection when
// elements may not be distinct
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to find intersection
void intersection(int a[], int b[], int n, int m)
{
    int i = 0, j = 0;
    while (i < n && j < m) {
        if (a[i] > b[j]) {
            j++;
        }
        else if (b[j] > a[i]) {
            i++;
        }
        else {
              
            // when both are equal
            cout << a[i] << " ";
            i++;
            j++;
        }
    }
}
  
// Driver Code
int main()
{
    int a[] = { 1, 3, 2, 3, 3, 4, 5, 5, 6 };
    int b[] = { 3, 3, 5 };
  
    int n = sizeof(a) / sizeof(a[0]);
    int m = sizeof(b) / sizeof(b[0]);
    
    // sort
    sort(a, a + n);
    sort(b, b + m);
    
    // Function call
    intersection(a, b, n, m);
}

Java




// Java code to find intersection when
// elements may not be distinct
  
import java.io.*;
import java.util.Arrays;
  
class GFG {
  
    // Function to find intersection
    static void intersection(int a[], int b[], int n, int m)
    {
        int i = 0, j = 0;
  
        while (i < n && j < m) {
  
            if (a[i] > b[j]) {
                j++;
            }
  
            else if (b[j] > a[i]) {
                i++;
            }
            else {
                // when both are equal
                System.out.print(a[i] + " ");
                i++;
                j++;
            }
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int a[] = { 1, 3, 2, 3, 4, 5, 5, 6 };
        int b[] = { 3, 3, 5 };
  
        int n = a.length;
        int m = b.length;
        
        // sort
        Arrays.sort(a);
        Arrays.sort(b);
        
        // Function call
        intersection(a, b, n, m);
    }
}

Python3




# Python 3 code to find intersection
# when elements may not be distinct
  
# Function to find intersection
  
  
def intersection(a, b, n, m):
  
    i = 0
    j = 0
  
    while (i < n and j < m):
  
        if (a[i] > b[j]):
            j += 1
  
        else:
            if (b[j] > a[i]):
                i += 1
  
            else:
                # when both are equal
                print(a[i], end=" ")
                i += 1
                j += 1
  
  
# Driver Code
if __name__ == "__main__":
  
    a = [1, 3, 2, 3, 4, 5, 5, 6]
    b = [3, 3, 5]
  
    n = len(a)
    m = len(b)
      
    # sort
    a.sort()
    b.sort()
      
    # function call
    intersection(a, b, n, m)
  
# This code is contributed by Ita_c

C#




// C# code to find intersection when
// elements may not be distinct
  
using System;
  
class GFG {
  
    // Function to find intersection
    static void intersection(int[] a, int[] b, int n, int m)
    {
        int i = 0, j = 0;
  
        while (i < n && j < m) {
  
            if (a[i] > b[j]) {
                j++;
            }
  
            else if (b[j] > a[i]) {
                i++;
            }
            else {
                // when both are equal
                Console.Write(a[i] + " ");
                i++;
                j++;
            }
        }
    }
  
    // Driver Code
    public static void Main()
    {
        int[] a = { 1, 3, 2, 3, 4, 5, 5, 6 };
        int[] b = { 3, 3, 5 };
  
        int n = a.Length;
        int m = b.Length;
        
        // sort
        Array.Sort(a);
        Array.Sort(b);
        
        // Function call
        intersection(a, b, n, m);
    }
}
// this code is contributed by mukul singh

PHP




<?php
// PHP code to find intersection when
// elements may not be distinct
  
// Function to find intersection
function intersection($a, $b, $n, $m)
{
    $i = 0; $j = 0;
      
    while ($i < $n && $j < $m
    {
                  
        if ($a[$i] > $b[$j]) 
        {
            $j++;
        
                  
        else
        if ($b[$j] > $a[$i]) 
        {
            $i++;
        
        else
        {
            // when both are equal
            echo($a[$i] . " ");
            $i++;
            $j++;
        }
    }
}
  
// Driver Code
$a = array(1, 3, 2, 3, 4, 5, 5, 6);
$b = array(3, 3, 5);
  
$n = sizeof($a);
$m = sizeof($b);
  
// sort
sort($a);
sort($b);
  
// Function call
intersection($a, $b, $n, $m);
  
// This code is contributed 
// by Mukul Singh
?>

Javascript




<script>
// Javascript code to find intersection when
// elements may not be distinct
  
    // Function to find intersection
    function intersection(a,b,n,m)
    {
        let i = 0, j = 0;
        while (i < n && j < m)
        {
            if (a[i] > b[j])
            {
                j++;
            }
            else if (b[j] > a[i])
            {
                i++;
            }
            else
            {
                // when both are equal
                document.write(a[i] + " ");
                i++;
                j++;
            }
        }
    }
      
    // Driver Code
    let a = [1, 3, 2, 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
    intersection(a, b, n, m);
      
    // This code is contributed by rag2127
</script>

Output

3 3 5 

 Thanks, Sanny Kumar for suggesting the above method.

Method 6(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

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

Intersection

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

C++




#include <bits/stdc++.h>
  
using namespace std;
  
// Function to find union
  
void Union(int a[], int b[], int n, int m)  {
          
          
        int *result=new int[n+m];
          
        int index=0;
        int 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++;
               }
        }
            
          cout<<"Union: ";
          for(int k=0;k<index;k++)
              cout<<result[k]<<" ";
          cout<<endl;
        
          
          
      
};
  
// Function to find intersection
void intersection(int a[], int b[], int n, int m) {
          
          
        int i=0,j=0,k=0;
        int *result=new int[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++;
            }
        }
        }
          cout<<"Intersection: ";
          for(int x=0;x<k;x++)
              cout<<result[x]<<" ";
          cout<<endl;
          
          
    }
  
  
// Driver Code
int main()
{
    int a[] = { 1, 3, 2, 3, 3, 4, 5, 5, 6 };
    int b[] = { 3, 3, 5 };
  
    int n = sizeof(a) / sizeof(a[0]);
    int m = sizeof(b) / sizeof(b[0]);
    
    // sort
    sort(a, a + n);
    sort(b, b + m);
    
    // Function call
      Union(a,b,n,m);
    intersection(a, b, n, m);
}

Method 7 (Use Hashing) 
Union 

  1. Initialize an empty hash set hs.
  2. Iterate through the first array and put every element of the first array in the set S.
  3. Repeat the process for the second array.
  4. Print the set hs.

Intersection 

  1. Initialize an empty set hs.
  2. Iterate through the first array and put every element of the first array in the set S.
  3. For every element x of the second array, do the following :

Search x in the set hs. If x is present, then print it. Time complexity of this method is ?(m+n) under the assumption that hash table search and insert operations take ?(1) time.

Below is the implementation of the above idea:

C++




// CPP program to find union and intersection
// using sets
#include <bits/stdc++.h>
using namespace std;
  
// Prints union of arr1[0..n1-1] and arr2[0..n2-1]
void printUnion(int arr1[], int arr2[], int n1, int n2)
{
    set<int> hs;
  
    // Insert the elements of arr1[] to set hs
    for (int i = 0; i < n1; i++)
        hs.insert(arr1[i]);
  
    // Insert the elements of arr2[] to set hs
    for (int i = 0; i < n2; i++)
        hs.insert(arr2[i]);
  
    // Print the content of set hs
    for (auto it = hs.begin(); it != hs.end(); it++)
        cout << *it << " ";
    cout << endl;
}
  
// Prints intersection of arr1[0..n1-1] and
// arr2[0..n2-1]
void printIntersection(int arr1[], int arr2[], int n1,
                       int n2)
{
    set<int> hs;
  
    // Insert the elements of arr1[] to set S
    for (int i = 0; i < n1; i++)
        hs.insert(arr1[i]);
  
    for (int i = 0; i < n2; i++)
  
        // If element is present in set then
        // push it to vector V
        if (hs.find(arr2[i]) != hs.end())
            cout << arr2[i] << " ";
}
  
// Driver Program
int main()
{
    int arr1[] = { 7, 1, 5, 2, 3, 6 };
    int arr2[] = { 3, 8, 6, 20, 7 };
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
  
    // Function call
    printUnion(arr1, arr2, n1, n2);
    printIntersection(arr1, arr2, n1, n2);
  
    return 0;
}

Java




// Java program to find union and intersection
// using Hashing
import java.util.HashSet;
  
class Test {
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    static void printUnion(int arr1[], int arr2[])
    {
        HashSet<Integer> hs = new HashSet<>();
  
        for (int i = 0; i < arr1.length; i++)
            hs.add(arr1[i]);
        for (int i = 0; i < arr2.length; i++)
            hs.add(arr2[i]);
        System.out.println(hs);
    }
  
    // Prints intersection of arr1[0..m-1] and arr2[0..n-1]
    static void printIntersection(int arr1[], int arr2[])
    {
        HashSet<Integer> hs = new HashSet<>();
        HashSet<Integer> hs1 = new HashSet<>();
  
        for (int i = 0; i < arr1.length; i++)
            hs.add(arr1[i]);
  
        for (int i = 0; i < arr2.length; i++)
            if (hs.contains(arr2[i]))
                System.out.print(arr2[i] + " ");
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int arr1[] = { 7, 1, 5, 2, 3, 6 };
        int arr2[] = { 3, 8, 6, 20, 7 };
  
        // Function call
        System.out.println("Union of two arrays is : ");
        printUnion(arr1, arr2);
  
        System.out.println(
            "Intersection of two arrays is : ");
        printIntersection(arr1, arr2);
    }
}

Python




# Python program to find union and intersection
# using sets
  
  
def printUnion(arr1, arr2, n1, n2):
    hs = set()
  
    # Insert the elements of arr1[] to set hs
    for i in range(0, n1):
        hs.add(arr1[i])
  
    # Insert the elements of arr1[] to set hs
    for i in range(0, n2):
        hs.add(arr2[i])
    print("Union:")
    for i in hs:
        print(i, end=" ")
    print("\n")
  
    # Prints intersection of arr1[0..n1-1] and
    # arr2[0..n2-1]
  
  
def printIntersection(arr1, arr2, n1, n2):
    hs = set()
  
    # Insert the elements of arr1[] to set S
    for i in range(0, n1):
        hs.add(arr1[i])
    print("Intersection:")
    for i in range(0, n2):
  
        # If element is present in set then
        # push it to vector V
        if arr2[i] in hs:
            print(arr2[i], end=" ")
  
  
# Driver Program
arr1 = [7, 1, 5, 2, 3, 6]
arr2 = [3, 8, 6, 20, 7]
n1 = len(arr1)
n2 = len(arr2)
  
# Function call
printUnion(arr1, arr2, n1, n2)
printIntersection(arr1, arr2, n1, n2)
  
# This article is contributed by Kumar Suman .

C#




// C# program to find union and intersection
// using Hashing
using System;
using System.Linq;
using System.Collections.Generic;
  
class GFG
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    static void printUnion(int []arr1, int []arr2)
    {
        HashSet<int> hs = new HashSet<int>();
          
        for (int i = 0; i < arr1.Length; i++) 
            hs.Add(arr1[i]);     
        for (int i = 0; i < arr2.Length; i++) 
            hs.Add(arr2[i]);
      
            Console.WriteLine(string.Join(", ", hs));     
    }
      
    // Prints intersection of arr1[0..m-1] and arr2[0..n-1]
    static void printIntersection(int []arr1, int []arr2)
    {
        HashSet<int> hs = new HashSet<int>();
          
        for (int i = 0; i < arr1.Length; i++) 
            hs.Add(arr1[i]);
          
        for (int i = 0; i < arr2.Length; i++) 
            if (hs.Contains(arr2[i]))
            Console.Write(arr2[i] + " ");
    }
      
    // Driver Code
    static void Main() 
    {
        int []arr1 = {7, 1, 5, 2, 3, 6};
        int []arr2 = {3, 8, 6, 20, 7};
  
        Console.WriteLine("Union of two arrays is : ");
        printUnion(arr1, arr2);
      
        Console.WriteLine("\nIntersection of two arrays is : ");
        printIntersection(arr1, arr2); 
    }
}
  
// This code is contributed by mits

Javascript




<script>
// javascript program to find union and intersection
// using Hashing
  
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    function printUnion(arr1 , arr2) {
        var hs = new Set();
  
        for (i = 0; i < arr1.length; i++)
            hs.add(arr1[i]);
        for (i = 0; i < arr2.length; i++)
            hs.add(arr2[i]);
            
           for(var k of hs)
            document.write(k+" ");
    }
  
    // Prints intersection of arr1[0..m-1] and arr2[0..n-1]
    function printIntersection(arr1 , arr2) {
        var hs = new Set();
        var hs1 = new Set();
  
        for (i = 0; i < arr1.length; i++)
            hs.add(arr1[i]);
  
        for (var i = 0; i < arr2.length; i++)
            if (hs.has(arr2[i]))
                document.write(arr2[i] + " ");
    }
  
    // Driver code
      
        var arr1 = [ 7, 1, 5, 2, 3, 6 ];
        var arr2 = [ 3, 8, 6, 20, 7 ];
  
        // Function call
        document.write("Union of two arrays is :<br/> ");
        printUnion(arr1, arr2);
  
        document.write("<br/>Intersection of two arrays is : <br/>");
        printIntersection(arr1, arr2);
  
// This code is contributed by gauravrajput1
</script>

Output

1 2 3 5 6 7 8 20 
3 6 7 

This method is contributed by Ankur Singh.
The time complexity of this method is O(m+n) under the assumption that hash table search and insert operations take O(1) time.

Method 8 (Kind of hashing technique without using any predefined Java Collections) 

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

Below is the implementation of the above code: 

C++




// CPP program to find union and intersection
  
#include <bits/stdc++.h>
using namespace std;
  
// Prints union of arr1[0..n1-1] and arr2[0..n2-1]
void printUnion(int v, int ans[], int zero)
{
    int zero1 = 0;
    cout<<"\nUnion : ";
    for (int i = 0; i < v; i++) {
        if ((zero == 0 && ans[i] == 0)
            || (ans[i] == 0 && zero1 > 0))
            continue;
        if (ans[i] == 0)
            zero1++;
       cout<<ans[i] << ",";
    }
}
  
void placeValue(int a[], int ans[], int i, int p, int v)
{
    p = p % v;
    if (ans[p] == 0)
        ans[p] = a[i];
    else {
        if (ans[p] == a[i])
            cout<<a[i] << ",";
        else {
  
            // Hashing collision happened increment
            // position and do recursive call
            p = p + 1;
            placeValue(a, ans, i, p, v);
        }
    }
}
  
  
void placeZeros(int v, int ans[], int zero)
{
    if (zero == 2) {
        cout<<"0"<<endl;
        int d[] = { 0 };
        placeValue(d, ans, 0, 0, v);
    }
    if (zero == 1) {
        int d[] = { 0 };
        placeValue(d, ans, 0, 0, v);
    }
}
  
  
// Function to iterate array
int iterateArray(int a[], int v, int ans[], int i)
{
    if (a[i] != 0) {
        int p = a[i] % v;
        placeValue(a, ans, i, p, v);
    }
    else
        return 1;
    return 0;
}
  
  
// Prints intersection of arr1[0..n1-1] and
// arr2[0..n2-1]
void findPosition(int a[], int b[], int n1, int n2)
{
    int v = (n1+n2);
    int ans[v];
    for(int i=0;i<v;i++)
    {
        ans[i]=0;
    }
      
    int zero1 = 0;
    int zero2 = 0;
  
    cout<<"Intersection : ";
    // Iterate first array
    for (int i = 0; i < n1; i++)
        zero1 = iterateArray(a, v, ans, i);
  
    // Iterate second array
    for (int j = 0; j < n2; j++)
        zero2 = iterateArray(b, v, ans, j);
  
    int zero = zero1 + zero2;
    placeZeros(v, ans, zero);
    printUnion(v, ans, zero);
}
   
// Driver Program
int main()
{
    int arr1[] = { 7, 1, 5, 2, 3, 6 };
    int arr2[] = { 3, 8, 6, 20, 7 };
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
   
    // Function call
    findPosition(arr1, arr2, n1, n2);
   
    return 0;
}
  
// This code is contributed by Aarti_Rathi

Java




// Java program to find union and intersection
// using similar Hashing Technique
// without using any predefined Java Collections
// Time Complexity best case & avg case = O(m+n)
// Worst case = O(nlogn)
  
// package com.arrays.math;
  
public class UnsortedIntersectionUnion {
  
    // Prints intersection of arr1[0..n1-1] and
    // arr2[0..n2-1]
    public void findPosition(int a[], int b[])
    {
        int v = (a.length + b.length);
        int ans[] = new int[v];
  
        int zero1 = 0;
        int zero2 = 0;
  
        System.out.print("Intersection : ");
        // Iterate first array
        for (int i = 0; i < a.length; i++)
            zero1 = iterateArray(a, v, ans, i);
  
        // Iterate second array
        for (int j = 0; j < b.length; j++)
            zero2 = iterateArray(b, v, ans, j);
  
        int zero = zero1 + zero2;
        placeZeros(v, ans, zero);
        printUnion(v, ans, zero);
    }
  
    // Prints union of arr1[0..n1-1] and arr2[0..n2-1]
    private void printUnion(int v, int[] ans, int zero)
    {
        int zero1 = 0;
        System.out.print("\nUnion : ");
        for (int i = 0; i < v; i++) {
            if ((zero == 0 && ans[i] == 0)
                || (ans[i] == 0 && zero1 > 0))
                continue;
            if (ans[i] == 0)
                zero1++;
            System.out.print(ans[i] + ",");
        }
    }
  
    private void placeZeros(int v, int[] ans, int zero)
    {
        if (zero == 2) {
            System.out.println("0");
            int d[] = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
        if (zero == 1) {
            int d[] = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
    }
  
    // Function to iterate array
    private int iterateArray(int[] a, int v, int[] ans,
                             int i)
    {
        if (a[i] != 0) {
            int p = a[i] % v;
            placeValue(a, ans, i, p, v);
        }
        else
            return 1;
        return 0;
    }
  
    private void placeValue(int[] a, int[] ans, int i,
                            int p, int v)
    {
        p = p % v;
        if (ans[p] == 0)
            ans[p] = a[i];
        else {
            if (ans[p] == a[i])
                System.out.print(a[i] + ",");
            else {
  
                // Hashing collision happened increment
                // position and do recursive call
                p = p + 1;
                placeValue(a, ans, i, p, v);
            }
        }
    }
  
    // Driver code
    public static void main(String args[])
    {
        int a[] = { 7, 1, 5, 2, 3, 6 };
        int b[] = { 3, 8, 6, 20, 7 };
  
        // Function call
        UnsortedIntersectionUnion uiu
            = new UnsortedIntersectionUnion();
        uiu.findPosition(a, b);
    }
}
// This code is contributed by Mohanakrishnan S.

Python3




# Python3 program to find union and intersection 
# using similar Hashing Technique 
# without using any predefined Java Collections
# Time Complexity best case & avg case = O(m+n)
# Worst case = O(nlogn)
  
  
# Prints intersection of arr1[0..n1-1] and
# arr2[0..n2-1]
def findPosition(a, b):
    v = len(a) + len(b);
    ans = [0]*v;
    zero1 = zero2 = 0;
    print("Intersection :",end=" ");
      
    # Iterate first array
    for i in range(len(a)):
        zero1 = iterateArray(a, v, ans, i);
      
    # Iterate second array
    for j in range(len(b)):
        zero2 = iterateArray(b, v, ans, j);
      
    zero = zero1 + zero2;
    placeZeros(v, ans, zero);
    printUnion(v, ans, zero);
      
# Prints union of arr1[0..n1-1] and arr2[0..n2-1]
def printUnion(v, ans,zero):
    zero1 = 0;
    print("\nUnion :",end=" ");
    for i in range(v):
        if ((zero == 0 and ans[i] == 0) or
            (ans[i] == 0 and zero1 > 0)):
            continue;
        if (ans[i] == 0):
            zero1+=1;
        print(ans[i],end=",");
  
def placeZeros(v, ans, zero):
    if (zero == 2):
        print("0");
        d = [0];
        placeValue(d, ans, 0, 0, v);
    if (zero == 1):
        d=[0];
        placeValue(d, ans, 0, 0, v);
  
# Function to iterate array
def iterateArray(a,v,ans,i):
    if (a[i] != 0):
        p = a[i] % v;
        placeValue(a, ans, i, p, v);
    else:
        return 1;
      
    return 0;
  
def placeValue(a,ans,i,p,v):
    p = p % v;
    if (ans[p] == 0):
        ans[p] = a[i];
    else:
        if (ans[p] == a[i]):
            print(a[i],end=",");
        else:
            # Hashing collision happened increment 
            # position and do recursive call
            p = p + 1;
            placeValue(a, ans, i, p, v);
  
# Driver code
a = [ 7, 1, 5, 2, 3, 6 ];
b = [ 3, 8, 6, 20, 7 ];
findPosition(a, b);
  
# This code is contributed by mits

C#




// C# program to find union and intersection 
// using similar Hashing Technique 
// without using any predefined Java Collections
// Time Complexity best case & avg case = O(m+n)
// Worst case = O(nlogn)
  
//package com.arrays.math;
using System;
class UnsortedIntersectionUnion 
{
  
        // Prints intersection of arr1[0..n1-1] and
        // arr2[0..n2-1]
    public void findPosition(int []a, int []b)
    {
        int v = (a.Length + b.Length);
        int []ans = new int[v];
  
        int zero1 = 0;
        int zero2 = 0;
  
        Console.Write("Intersection : ");
          
        // Iterate first array
        for (int i = 0; i < a.Length; i++)
            zero1 = iterateArray(a, v, ans, i);
  
        // Iterate second array
        for (int j = 0; j < b.Length; j++)
            zero2 = iterateArray(b, v, ans, j);
  
        int zero = zero1 + zero2;
        placeZeros(v, ans, zero);
        printUnion(v, ans, zero);
  
    }
      
    // Prints union of arr1[0..n1-1] 
    // and arr2[0..n2-1]
    private void printUnion(int v, int[] ans, int zero)
    {
        int zero1 = 0;
        Console.Write("\nUnion : ");
        for (int i = 0; i < v; i++) 
        {
            if ((zero == 0 && ans[i] == 0) || 
                    (ans[i] == 0 && zero1 > 0))
                continue;
            if (ans[i] == 0)
                zero1++;
            Console.Write(ans[i] + ",");
        }
    }
  
    private void placeZeros(int v, int[] ans, int zero)
    {
        if (zero == 2) 
        {
            Console.WriteLine("0");
            int []d = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
        if (zero == 1) 
        {
            int []d = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
    }
  
    // Function to iterate array
    private int iterateArray(int[] a, int v, 
                            int[] ans, int i)
    {
        if (a[i] != 0) 
        {
            int p = a[i] % v;
            placeValue(a, ans, i, p, v);
        } else
            return 1;
        return 0;
    }
  
    private void placeValue(int[] a, int[] ans, 
                                int i, int p, int v) 
    {
        p = p % v;
        if (ans[p] == 0)
            ans[p] = a[i];
        else {
            if (ans[p] == a[i])
                Console.Write(a[i] + ",");
            else
            {
                  
                //Hashing collision happened increment 
                // position and do recursive call
                p = p + 1;
                placeValue(a, ans, i, p, v);
            }
        }
    }
  
    // Driver code
    public static void Main() 
    {
        int []a = { 7, 1, 5, 2, 3, 6 };
        int []b = { 3, 8, 6, 20, 7 };
  
        UnsortedIntersectionUnion uiu = new UnsortedIntersectionUnion();
        uiu.findPosition(a, b);
    }
}
  
// This code is contributed by PrinciRaj1992

Javascript




<script>
// javascript program to find union and intersection
// using similar Hashing Technique
// without using any predefined javascript Collections
// Time Complexity best case & avg case = O(m+n)
// Worst case = O(nlogn)
  
// package com.arrays.math;
  
    // Prints intersection of arr1[0..n1-1] and
    // arr2[0..n2-1]
     function findPosition(a , b) {
        var v = (a.length + b.length);
        var ans = Array(v).fill(0);
  
        var zero1 = 0;
        var zero2 = 0;
  
        document.write("Intersection : ");
        // Iterate first array
        for (var i = 0; i < a.length; i++)
            zero1 = iterateArray(a, v, ans, i);
  
        // Iterate second array
        for (var j = 0; j < b.length; j++)
            zero2 = iterateArray(b, v, ans, j);
  
        var zero = zero1 + zero2;
        placeZeros(v, ans, zero);
        printUnion(v, ans, zero);
    }
  
    // Prints union of arr1[0..n1-1] and arr2[0..n2-1]
     function printUnion(v,  ans , zero) {
        var zero1 = 0;
        document.write("<br/>Union : ");
        for (i = 0; i < v; i++) {
            if ((zero == 0 && ans[i] == 0) || (ans[i] == 0 && zero1 > 0))
                continue;
            if (ans[i] == 0)
                zero1++;
            document.write(ans[i] + ",");
        }
    }
  
     function placeZeros(v,  ans , zero) {
        if (zero == 2) {
            document.write("0");
            var d = [ 0 ];
            placeValue(d, ans, 0, 0, v);
        }
        if (zero == 1) {
            var d = [ 0 ];
            placeValue(d, ans, 0, 0, v);
        }
    }
  
    // Function to iterate array
     function iterateArray(a , v,  ans , i) {
        if (a[i] != 0) {
            var p = a[i] % v;
            placeValue(a, ans, i, p, v);
        } else
            return 1;
        return 0;
    }
  
     function placeValue(a,  ans , i , p , v) {
        p = p % v;
        if (ans[p] == 0)
            ans[p] = a[i];
        else {
            if (ans[p] == a[i])
                document.write(a[i] + ",");
            else {
  
                // Hashing collision happened increment
                // position and do recursive call
                p = p + 1;
                placeValue(a, ans, i, p, v);
            }
        }
    }
  
    // Driver code
        var a = [ 7, 1, 5, 2, 3, 6 ];
        var b = [ 3, 8, 6, 20, 7 ];
  
        // Function call
        findPosition(a, b);
  
// This code is contributed by gauravrajput1 
</script>

Output

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

C++




// C++ program to find union and intersection
//  using sets
  
#include <bits/stdc++.h>
using namespace std;
  
void printUnion(int arr1[], int arr2[], int n1, int n2)
{
    // Defining set container s
    set<int> s;
      
    //  Insert the elements of arr1[] to set s
    for (int i = 0; i < n1; i++)
    {
        s.insert(arr1[i]);
    }
      
    //  Insert the elements of arr2[] to set s
    for (int i = 0; i < n2; i++)
    {
        s.insert(arr2[i]);
    }
      
    cout << "Union:" << endl;
    for (auto itr = s.begin(); itr != s.end(); itr++)
        // s will contain only distinct
        // elements from array a and b
        cout << *itr<< " "
          
    cout <<endl;
    //  Prints intersection of arr1[0..n1-1] and
    //  arr2[0..n2-1]
}
  
void printIntersection(int arr1[], int arr2[], int n1, int n2)
{
    // Defining set container s
    set<int> s;
      
    //  Insert the elements of arr1[] to set s
    for (int i = 0; i < n1; i++)
    {
        s.insert(arr1[i]);
    }
      
    cout << "Intersection:" << endl;
      
    for (int i = 0; i < n2; i++)
    {
        // If element is present in set then
        if(s.count(arr2[i]))
        {
            cout<<arr2[i]<<" ";
        }
    }
          
    cout <<endl;
}
  
// Driver Code
int main()
{
    int arr1[] = { 7, 1, 5, 2, 3, 6 };
    int arr2[] = { 3, 8, 6, 20, 7 };
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
  
    printUnion(arr1, arr2, n1, n2);
    printIntersection(arr1, arr2, n1, n2);
}
  
// This code is contributed by Aarti_Rathi

Java




// Java program to find union and intersection
// using sets
  
import java.util.*;
  
public class GFG {
  
  static void printUnion(int arr1[], int arr2[], int n1,
                         int n2)
  {
    // Defining set container s
    Set<Integer> s = new HashSet<Integer>();
  
    //  Insert the elements of arr1[] to set s
    for (int i = 0; i < n1; i++) {
      s.add(arr1[i]);
    }
  
    //  Insert the elements of arr2[] to set s
    for (int i = 0; i < n2; i++) {
      s.add(arr2[i]);
    }
  
    System.out.println("Union");
    for (int itr : s)
      // s will contain only distinct
      // elements from array a and b
      System.out.print(itr + " ");
  
    System.out.println();
  }
  
  static void printIntersection(int arr1[], int arr2[],
                                int n1, int n2)
  {
    // Defining set container s
    Set<Integer> s = new HashSet<Integer>();
  
    //  Insert the elements of arr1[] to set s
    for (int i = 0; i < n1; i++) {
      s.add(arr1[i]);
    }
  
    System.out.println("Intersection");
  
    for (int i = 0; i < n2; i++) {
      // If element is present in set then
      if (s.contains(arr2[i])) {
        System.out.print(arr2[i] + " ");
      }
    }
  
    System.out.println();
  }
  
  // Driver code
  public static void main(String args[])
  {
    int arr1[] = { 7, 1, 5, 2, 3, 6 };
    int arr2[] = { 3, 8, 6, 20, 7 };
    int n1 = arr1.length;
    int n2 = arr2.length;
  
    // Function call
    printUnion(arr1, arr2, n1, n2);
    printIntersection(arr1, arr2, n1, n2);
  }
}
// This code is contributed by Aarti_Rathi

Python3




#  Python program to find union and intersection
#  using sets
  
  
def printUnion(arr1, arr2, n1, n2):
    hs = set()
    #  Insert the elements of arr1[] to set hs
    for i in range(0, n1):
        hs.add(arr1[i])
    #  Insert the elements of arr1[] to set hs
    for i in range(0, n2):
        hs.add(arr2[i])
    print("Union:")
    for i in hs:
        print(i, end=" ")
    print("\n")
    #  Prints intersection of arr1[0..n1-1] and
    #  arr2[0..n2-1]
  
  
def printIntersection(arr1, arr2, n1, n2):
    hs = set()
    #  Insert the elements of arr1[] to set S
    for i in range(0, n1):
        hs.add(arr1[i])
    print("Intersection:")
    for i in range(0, n2):
        #  If element is present in set then
        #  push it to vector V
        if arr2[i] in hs:
            print(arr2[i], end=" ")
  
  
#  Driver Program
arr1 = [7, 1, 5, 2, 3, 6]
arr2 = [3, 8, 6, 20, 7]
n1 = len(arr1)
n2 = len(arr2)
  
# Function call
printUnion(arr1, arr2, n1, n2)
printIntersection(arr1, arr2, n1, n2)
  
# This code is contributed by Kumar Suman .

Output

Union:
1 2 3 5 6 7 8 20 

Intersection:
3 6 7 

See the following post for sorted arrays. Find Union and Intersection of two sorted arrays


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!