Problem
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.
Examples
Example 1:
| |
Example 2:
| |
Follow ups
What if arrays are sorted
We have solved it here, Intersection of Two Sorted Arrays, and also in method 2.
What if elements in nums2 cannot fit in memory
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?
- Store
nums1in aMap. - Split
nums2intonequal chunks. - Load one chunk of
nums2into memory at a time and check for intersections with theMap. If the intersection result becomes too large for memory, save the partial result to disk and proceed with the process.
What if elements in both nums1 and nums2 cannot fit in memory
- Utilize external sorting to sort
nums1. - Similarly, apply external sorting to sort
nums2(this can theoretically be done concurrently with the sorting ofnums1). - Implement the two-pointer method to find the intersection:
- Partition
nums1into chunks that use no more than ~10% of memory. - Similarly, partition
nums2into chunks that also use no more than ~10% of memory. - Dedicate the remaining ~80% of memory for the intersection results.
- Simultaneously load one chunk of
nums1and one chunk ofnums2into memory. - If the intersection becomes too large for memory, save the partial result to disk and proceed with the algorithm.
- Partition
Solution
Method 1 - Frequency map
Here are the steps we can follow:
- Create the frequency map on nums1
- Now, loop over nums2 and check if element exists in map
- If it does, add to answer list and reduce the frequency in frequency map
- If it doesn’t exist in map, just continue
- Finally convert the answer list to array and return
Code
| |
Complexity
- ⏰ Time complexity:
O(m + n)wheremandnis size of ofnums1andnums2. - 🧺 Space complexity:
O(m + n)
Method 2 - Sorting and two pointer scan
Here are the steps we can follow:
- Sort both arrays
- Now start 2 pointers
iandjon both the arrays.- If the elements are not equal, move the pointer forward with smaller value
- If the
nums[i]andnums[j]elements are equal, we add to answer list
- Convert answer list to array and return
If the arrays are sorted, we just need to follow the steps from step 2: Intersection of Two Sorted Arrays
Code
| |
Complexity
- ⏰ Time complexity:
O(m log m + n log n)wheremandnis size of ofnums1andnums2. Mainly, for sorting two arrays andO(n log m)for searching elements elements innums1innums2. - 🧺 Space complexity:
O(n)for usingansList