Intersection of Two Arrays II

Easy
3
44.2% Acceptance

In this lab, you will be implementing a function to find the intersection of two integer arrays, nums1 and nums2. The intersection of these arrays should contain elements that are present in both arrays. 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.

For example, let's consider the following two integer arrays:

  • nums1 = [1, 2, 2, 1]
  • nums2 = [2, 2]

The intersection of these arrays will be [2, 2] because the number 2 is present twice in both arrays.

Here is another example:

  • nums1 = [4, 9, 5]
  • nums2 = [9, 4, 9, 8, 4]

The intersection of these arrays could either be [9, 4] or [4, 9]. Both are accepted since the order does not matter, but the numbers 9 and 4 appear in both arrays.

Constraints:

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

Follow up:

Consider these additional questions to improve the performance of your solution:

  • 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?

Challenges

  1. Export the intersect function from your index.js file.
  2. Correctly implement the intersect function to find the intersection of two integer arrays.
  3. Test the intersect function with different inputs to ensure it works correctly.