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

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala