Intersection of Two Arrays Leetcode Solution

Hello coders, Today we are going to solve another problem of Leetcode ” Intersection of Two Arrays Leetcode Solution “. In this blog, we will how to solve this problem in java. I hope you have already read the problem statement and if not please do check below.

Problem statement:

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.


Intersection of Two Arrays Leetcode Solution java

import java.util.*;
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> hs1=new HashSet<Integer>();
        HashSet<Integer> hs2=new HashSet<Integer>();
        int n=nums1.length;
        int m=nums2.length;
        if(n>m){
            for(int i=0;i<m;i++){
                hs1.add(nums2[i]);
            }
            for(int i=0;i<n;i++){
                if(hs1.contains(nums1[i]))
                hs2.add(nums1[i]);
            }
        }
        else{
            for(int i=0;i<n;i++){
                hs1.add(nums1[i]);
            }
            for(int i=0;i<m;i++){
                if(hs1.contains(nums2[i]))
                hs2.add(nums2[i]);
            }
        }
        int arr[]=new int[hs2.size()];
            int j=0;
        for( int i:hs2){
            arr[j]=i;
            j++;
        }
        return arr;
        
        
    }
}

.

Disclaimer: This problem(Intersection of Two Arrays) is originally created by Leetcode. Codesagar only provides a solution for it. This solution is only for Educational and learning purposes.

Leave a Comment