Intersection of Two Arrays II

The Intersection of Two Arrays II (Leet Code)

This article is another part of a series on leet code problems solutions, and it provides a solution to the leet code  Intersection of Two Arrays II. This is a Leet code problem named two Sum. We will solve it using python and it is the best space and time-optimized solution. 

Question of Intersection of Two Arrays

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.

Question Explaination

Here in this question, we have to find the intersection of two arrays. So we have to find the numbers of the second array are present in the first array or not and print the numbers which are present in both the array.

Example

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.
Example 3

Input: nums =nums1  =[1,3,8,9,3]
nums2  = [1,0]
Output: [1]

Constraints

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

Approach to solve Intersection of Two Arrays Problem

To solve this question first we will sort both the arrays.  After this, we will run the while loop until we reach at the end of any of the arrays. Inside while loop we check three conditions:

  1. If both the values are equal then save the value in list and increment pointer i and j by 1.
  2. If value of nums1 at position i is greater than the value of nums2 at then we increment the value of j by 1.
  3. If value of nums1 at position i is less than the value of nums2 at then we increment the value of j by 1.

Variables and its usage

We will only use 3 variables here.

  1. ret[] of type list to store the same values of both arrays.
  2. Variable as a pointer to nums1 array.
  3. variable as a pointer to nums2 array.

Python Code for Intersection of Two Arrays

 
def intersect( nums1, nums2):
    nums2.sort()
    nums1.sort()
    ret=[]
 
    i=0
    j=0
    while(len(nums1) >i and (len(nums2) >j)):
        if(nums1[i] == nums2[j]):
            ret.append(nums2[j])
            i+=1
            j+=1
        elif(nums1[i] > nums2[j]):
            j+=1
        elif(nums1[i] < nums2[j]):
            i+=1
    return ret
                          
nums1  =[1,2,2,1]
nums2  = [2,2]

print(intersect( nums1, nums2))

nums1  =[1,2]
nums2  = [1,1]
print(intersect( nums1, nums2))

nums1  =[4,9,5]
nums2  = [9,4,9,8,4]
print(intersect( nums1, nums2))

nums1  =[1,3,8,9,3]
nums2  = [1,0]
print(intersect( nums1, nums2))

Output

Intersection of Two Arrays II

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Leave A Comment

Your email address will not be published. Required fields are marked *