Intersection of Two Arrays Solution - The Coding Shala

Home >> Interview Questions >> Intersection of two arrays

Intersection of Two Arrays Solution

In this post, you will learn how to find the intersection of two arrays and its solution in Java.

Given two arrays, write a function to compute their intersection.
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]

Note: Each element in the result must be unique. The result can be in any order.

Java Program to find the Intersection of Two Arrays

Approach 1:
We can find the intersection of two arrays using two HashSets.
Java Program: 

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<Integer>();
        for(int num : nums1) set.add(num);
        Set<Integer> result = new HashSet<Integer>();
        for(int num : nums2){
            if(set.contains(num)){
                result.add(num);
            }
        }
        int[] ans = new int[result.size()];
        int i = 0;
        for(Integer val : result) ans[i++] = val;
        return ans;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

New Year Chaos Solution - The Coding Shala

Java Program to Find LCM of Two Numbers - The Coding Shala