HashTable

Intersection of Two given Arrays

Pinterest LinkedIn Tumblr

Write a program to find the intersection of Two given Arrays. The utility function takes two arrays and returns the intersection array.

Algorithm Explanation

Initialize the array1 and array2 with chars. Pass two char arrays to utility function and create two hash set.
Iterate all the element from array1 and add to set1.
Iterate all element from array2 and check with set1. If set1 contains the char, add in set2.
Return set2 and display the values.

Source Code

package com.dsacode.DataStructre.hashtable;
 import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
 public class IntersectionArray {
    private static Set < Character > intersect(char[] a, char[] b) {
        Set < Character > aSet = new HashSet < Character >();
        Set < Character > intersection = new HashSet < Character >();
        for (char c : a) {
            aSet.add(c);
        }
        for (char c : b) {
            if (aSet.contains(c)) {
                intersection.add(c);
            }
        }
        return intersection;
    }
    public static void main(String[] args) {
         
         char[] a = {'a', 'b', 'c', 'd'};
         System.out.println("Array 1 values: " + Arrays.toString(a));
          
         char[] b = {'c', 'd', 'e', 'f'};
         System.out.println("Array 2 values: " + Arrays.toString(b));
          
         System.out.println("Intersection of two arrays: "+intersect(a, b));
     }
 }

Output

Array 1 values: [a, b, c, d]
Array 2 values: [c, d, e, f]
Intersection of two arrays: [c, d]

Write A Comment