Logo

Kode$word

Intersection of Two Arrays II

Intersection of Two Arrays II

Leetcode question 350

14 views
0
0

LeetCode Problem 350

Link of the Problem to try -: Link


Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Example 1:

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

Example 2:

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

Constraints:

  1. 1 <= nums1.length, nums2.length <= 1000
  2. 0 <= nums1[i], nums2[i] <= 1000


Solution:

In this question we can build a frequency HashMap of each element and then add into the array as per it's frequency is that is a very important thing in this question to do.

For creating frequency we will use getOrDefault() method in HashMap that is very useful for creating frequency as this method returns the value of that key if that key is not exist then whatever value we give that value is considered as default value for us.

So, back to question here we simply create a map creating frequency of each element and if the element came again we simply increase the frequency of it then we create a ArrayList because we don't know about the size of array here so we use ArrayList after this we will iterate again on the second array and try to find that element in the map also we check it's frequency should be more than 0 and we add in the List also we decreasing the frequency of the element in the loop.

At last we simply take all the elements of ArrayList and put into a array of size of that ArrayList because our questions want's ans in array that's why we have to do this step otherwise our ans is in the ArrayList and this is how we find duplicates of the number of times that element appears in both array.


Code:

public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> mp = new HashMap<>();
for (int i = 0; i < nums1.length; i++) {
// If you are not interested in writing getOrDefault then you can write via if statement as well
// int cou =1;
// if(mp.containsKey(nums1[i])){
// // int nu = mp.get(nums1[i]);
// mp.put(nums1[i],mp.get(nums1[i])+1);
// continue;
// }
// mp.put(nums1[i],cou);

// Another way
mp.put(nums1[i], mp.getOrDefault(nums1[i], 0) + 1);

}
List<Integer> lis = new ArrayList<>();
for (int i = 0; i < nums2.length; i++) {
if (mp.containsKey(nums2[i]) && mp.get(nums2[i]) > 0) {
lis.add(nums2[i]);
}
mp.put(nums2[i], mp.getOrDefault(nums2[i], 0) - 1);
}
int[] ans = new int[lis.size()];
for (int i = 0; i < ans.length; i++) {
ans[i] = lis.get(i);
}
return ans;

}