350. Intersection of Two Arrays II(Solution || Leetcode easy || Java)

Palakkgoyal
2 min readNov 3, 2022

--

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 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

SOLUTION:

class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
//First we are going to sort our arrays
Arrays.sort(nums1);
Arrays.sort(nums2);

//initialising counter variable for both arrays
int i = 0;
int j = 0;

//initialising counter variable for duplicates
int k = 0;

//loop for duplicates
while(i < nums1.length && j < nums2.length){

//As the arrays are sorted if nums1 element is less than nums2 than it means that we won’t find that element int he left side of the array, so we have to move forward
if(nums1[i] < nums2[j]){
i++;
}

//Same concept for nums2 array as it for nums1
else if(nums1[i] > nums2[j]){
j++;
}

//If the element are equal we add in nums1(It’s your choice whether to add that element in nums1 or nums2), this is done to reduce space
else{
nums1[k++] = nums1[i++];
j++;
}
}

//This finction will return the array till kth index(the index till wich elements are duplicates)
return Arrays.copyOfRange(nums1,0,k);
}
}

Thank you for reading. If you have any queries then, lease let me know in the comment section, I will surely response toward that.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet