Quick actions

cmd+k|ctrl+k

Navigation

Languages

Intersection of two arrays

Snippet info

Language

Java

Visibility

public

Author

shraddharao-

Created

2024-02-27T16:02:01.715681Z

Updated

2024-02-27T16:02:01.715681Z


import java.util.*;
class Main {
    /*
    Write a function or program that takes two arrays of integers as input and
    returns an array containing all the elements that are common to both input arrays (i.e., the intersection).
    
    Array 1: [1, 2, 2, 1]
    Array 2: [2, 2]
    */
    
    // Store the elements of array1 using HashSet
    // iterate through the other array to find the common elements
    // check each element of other element is stored in the HashSet.
    
    public static int[] findCommonElement(int[] array1, int[] array2){
        Set<Integer> set = new HashSet<>();
        Set<Integer> result = new HashSet<>();
        
        // store element of array1
        for(int e : array1){
            set.add(e);
        }
        
        // iterate array2 to find common e
        for(int e : array2){
            if(set.contains(e)){
                result.add(e);
            }
        }
        
        // convert the result set into an array
        int[] intersection = new int[result.size()];
        int index = 0;
        for (int num : result){
            intersection[index++] = num;
        }
        return intersection;
        
    }
    public static void main(String[] args) {
        int[] array1 = {1,2,2,1};
        int[] array2 = {2,2};
        int[] isCommon = findCommonElement(array1,array2);
        System.out.println(Arrays.toString(isCommon));
    }
    
    /*
    Time Complexity: O(m+n), where m and n are the sizes of the input arrays.
    Space Complexity: O(m+k), where m is the number of unique elements in the first array, and 
                 k is the size of the intersection array.
    */
}
INFO