We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find the Difference of Two Arrays

Number: 1392

Difficulty: Easy

Paid? No

Companies: Google, Meta, Yandex, Amazon, Adobe


Problem Description

Given two 0-indexed integer arrays nums1 and nums2, return a list of two lists where:

  • The first list contains all distinct integers in nums1 that are not present in nums2.
  • The second list contains all distinct integers in nums2 that are not present in nums1. The order of the integers in each list does not matter.

Key Insights

  • Use sets to automatically remove duplicate elements.
  • Utilize set difference operations to find elements unique to each array.
  • Converting the set back to a list yields the required distinct elements.
  • The order of elements is not important.

Space and Time Complexity

Time Complexity: O(n + m) Space Complexity: O(n + m)


Solution

To solve the problem, first convert both input arrays into sets in order to store only distinct elements. Then, compute the difference between these sets to determine which elements are unique to each array. Finally, convert the resulting sets back into lists and return them in a list of two lists. This approach efficiently handles the removal of duplicates and the computation of differences.


Code Solutions

def findDifference(nums1, nums2):
    # Convert both lists to sets to remove duplicates
    set1 = set(nums1)
    set2 = set(nums2)
    
    # Find elements in nums1 not in nums2
    diff1 = list(set1 - set2)
    # Find elements in nums2 not in nums1
    diff2 = list(set2 - set1)
    
    return [diff1, diff2]

# Example test
print(findDifference([1, 2, 3], [2, 4, 6]))
← Back to All Questions