2215. Find the Difference of Two Arrays
Given two 0-indexed integer arrays nums1
and nums2
, return a list answer
of size 2 where:
answer[0]
is a list of all distinct integers in nums1
which are not present in nums2
.answer[1]
is a list of all distinct integers in nums2
which are not present in nums1
.Note that the integers in the lists may be returned in any order.
Input: nums1 = [1,2,3], nums2 = [2,4,6]
Output: [[1,3],[4,6]]
Explanation:
For nums1, nums1[1]=2 is present in nums2, so it is removed. Remaining items are [1, 3].
For nums2, nums2[0]=2 is present in nums1, so it is removed. Remaining items are [4, 6].
The goal is to find distinct integers in one array but not in the other array. Here are the step-by-step procedures:
set1 - set2
to get elements present in nums1
but not in nums2
.set2 - set1
to get elements present in nums2
but not in nums1
.nums1
and m is the length of nums2
.set1 - set2
and O(m) for set2 - set1
.Here is the implementation in Python:
def findDifference(nums1, nums2):
set1 = set(nums1)
set2 = set(nums2)
diff1 = list(set1 - set2)
diff2 = list(set2 - set1)
return [diff1, diff2]
Let’s run an example:
nums1 = [1, 2, 3]
nums2 = [2, 4, 6]
print(findDifference(nums1, nums2)) # Output should be [[1, 3], [4, 6]]
This correctly computes the distinct elements in each list according to the described strategy.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?