Math Fundamentals18 sections · 814 units
Open in Course

Intersection - Implementation

Hash set solution

Here is the solution:


function intersection(nums1, nums2)
    set1 := convert nums1 to set
    set2 := convert nums2 to set
    result := empty list
    for each element in set1
        if element in set2 then
            add element to result
    return result

You convert both arrays to sets, then iterate through one set and check membership in the other. Time: O(n+m)O(n + m), Space: O(n+m)O(n + m) where nn and mm are the array lengths.