Leetcode POTD - Intersection of Two Arrays II

·

2 min read

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.

Solution:

  1. This implementation sorts both arrays first and then uses a two-pointer technique to find the intersection elements.

  2. The ranges::sort function sorts both nums1 and nums2 in non-decreasing order. Sorting the arrays helps simplify the process of finding the intersection by allowing a linear scan to identify common elements

ranges::sort(nums1);
ranges::sort(nums2);
  1. result is the result vector that will store the intersection elements. i is an index variable for iterating through nums1. j is an index variable for iterating through nums2.
vector<int> result;
int i = 0;
int j = 0;
  1. This while loop continues as long as there are elements to compare in both nums1 and nums2 . if (nums1[i] < nums2[j]): If the current element in nums1 is less than the current element in nums2, increment i. This means the element in nums1 cannot be in the intersection, so we move to the next element in nums1 . else if (nums1[i] > nums2[j]): If the current element in nums1 is greater than the current element in nums2, increment j. This means the element in nums2 cannot be in the intersection, so we move to the next element in nums2. else: If the current elements in nums1 and nums2 are equal, it means we have found a common element. We add this element to result and increment both i and j to move to the next elements in both arrays.
while(i<nums1.size() && j<nums2.size()){
            if(nums1[i] < nums2[j]){
                ++i;
            }
            else if(nums1[i] > nums2[j]){
                ++j;
            }
            else{
                result.push_back(nums1[i]);
                ++i;
                ++j;
            }
        }
  1. Finally, the method returns the result vector containing the intersection of nums1 and nums2 .
return result;
  1. Here is the entire code:
class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        ranges::sort(nums1);
        ranges::sort(nums2);

        vector<int> result;
        int i=0;
        int j = 0;

        while(i<nums1.size() && j<nums2.size()){
            if(nums1[i] < nums2[j]){
                ++i;
            }
            else if(nums1[i] > nums2[j]){
                ++j;
            }
            else{
                result.push_back(nums1[i]);
                ++i;
                ++j;
            }
        }

        return result;

    }
};

Thank you ! Keep Learning :))