Find the Difference of Two Arrays

Here is a simple Python solution using sets.

Sets in Python are used to store multiple items in a single variable and they are one of the data types that Python offers. Set items are unordered, unchangeable, and do not allow duplicate values.

In this solution, we convert the input arrays to sets and then use the set difference operation to find the elements that are in one set but not the other. Here is the code:

1
2
3
4
class Solution:
    def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
        set1, set2 = set(nums1), set(nums2)
        return [list(set1 - set2), list(set2 - set1)]

In this code:

  1. We convert nums1 and nums2 to sets set1 and set2. This removes any duplicate elements and allows us to perform set operations.

  2. We use the - operator to compute the difference between the sets. set1 - set2 gives us all elements that are in set1 but not in set2, and set2 - set1 gives us all elements that are in set2 but not in set1.

  3. We convert the result back to a list, as the problem requires us to return a list of lists.

The time complexity of this solution is O(n), where n is the total number of elements in nums1 and nums2. This is because converting a list to a set takes linear time, and the set difference operation also takes linear time. The space complexity is also O(n), for storing the sets.