Math Fundamentals18 sections · 814 units
Open in Course

Difference - Implementation

Two set subtractions

Here is the solution:


function findDifference(nums1, nums2)
    set1 := convert nums1 to set
    set2 := convert nums2 to set
    answer1 := empty list
    answer2 := empty list
    for each element in set1
        if element not in set2 then
            add element to answer1
    for each element in set2
        if element not in set1 then
            add element to answer2
    return [answer1, answer2]

You compute both differences separately. Time: O(n+m)O(n + m), Space: O(n+m)O(n + m).