Problem
Given two sorted arrays, find the intersection (elements present in both arrays).
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Using two pointers
We will approach this similarly to the “merging” step in merge sort by traversing both sorted arrays simultaneously. Suppose nums1 is indexed by i and nums2 is indexed by j. Then:
- If
nums1[i] == nums2[j], add the element to the intersection. - If
nums1[i] > nums2[j], incrementj. - If
nums1[i] < nums2[j], incrementi.
The space complexity is equivalent to the size of the intersection, which is the minimum of m and n. This question isn’t particularly challenging, but overthinking could lead to failure to answer correctly, negatively impacting your impression.
We have already seen this solution here, but after sorting here - Intersection of Two Arrays 1 - Unique Elements#Method 3 - Binary Search.
Code
| |
Complexity
- ⏰ Time complexity:
O(m + n)wheremandnis size of ofnums1andnums2. - 🧺 Space complexity:
O(m)for usingansList