350_Intersection of Two Arrays II

[Easy][Array, Two Pointers, Binary Search, Hash Table, Sort]

Given two arrays, write a function to compute their intersection.

Note:

  • Each element in the result should appear as many times as it shows in both arrays.

  • The result can be in any order.

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?

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]

Idea:

  • Sort the two arrays first.

  • Loop over each element in one array, use binary search to find if that element exist in the other array.

  • We can choose smaller length array for the loop, such that the time complexity will be smaller.

  • This approach has advantage if one array is much smaller in size than the other one.

Time Complexity: O(mlogn)O(m \log{n}) or O(nlogm)O(n\log{m})

Space Complexity: O(1)O(1)

Solution 2: Sort + Two Pointers

Idea:

  • First sort the two arrays.

  • Simultaneously advance through the two arrays in increasing order. At each iteration:

    • If the two elements differ, eliminate the small one.

    • If they are the same, append to output and advance both.

  • If the length of two arrays are similar, this solution has advantage.

Time Complexity: O(mlogm+nlogn+m+n)O(m \log{m} + n \log{n} + m + n)

Space Complexity: O(1)O(1)

Solution 3: Dictionary

Idea:

  • Count frequency of each number in nums1, store in a dictionary.

  • Loop for each element in nums2, check if it has a pair in the dictionary. If yes, append the element, and decrease the corresponding frequency by 1.

Time Complexity: O(m+n)O(m+n)

Space Complexity: O(m)O(m) or O(n)O(n), can choose the smaller one.

Last updated

Was this helpful?