While a hash map is a common solution, the Two Pointer approach is extremely efficient if the arrays are sorted. We sort both arrays and use two pointers to find common elements.
- Sort
nums1andnums2. - Initialize
i = 0,j = 0,res = []. - While
i < len(nums1)andj < len(nums2):- If
nums1[i] < nums2[j], incrementi. - Else if
nums1[i] > nums2[j], incrementj. - Else:
- Append
nums1[i]tores. - Increment
iandj.
- Append
- If
- Return
res.
- Time Complexity: O(N log N + M log M) due to sorting.
- Space Complexity: O(N + M).
def intersect(nums1, nums2):
nums1.sort()
nums2.sort()
i = j = 0
res = []
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
i += 1
elif nums1[i] > nums2[j]:
j += 1
else:
res.append(nums1[i])
i += 1
j += 1
return res