2215. Find the Difference of Two Arrays
Problem
Return two lists: the distinct values of nums1 that aren't in nums2, and the distinct values of nums2 that aren't in nums1. Order within each list doesn't matter.
Example: nums1 = [1,2,3], nums2 = [2,4,6] → [[1,3],[4,6]]
Set difference both ways: set1 − set2 and set2 − set1 (duplicates collapse automatically). Either list may be returned in any order.
Complexity: O(n + m).
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
a, b = set(nums1), set(nums2)
return [list(a - b), list(b - a)]
assert [sorted(x) for x in Solution().findDifference([1, 2, 3], [2, 4, 6])] == [[1, 3], [4, 6]]
assert [sorted(x) for x in Solution().findDifference([1, 2, 3, 3], [1, 1, 2, 2])] == [[3], []]
assert [sorted(x) for x in Solution().findDifference([-1], [-1])] == [[], []]
class Solution {
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
Set<Integer> a = new HashSet<>(), b = new HashSet<>();
for (int x : nums1) a.add(x);
for (int x : nums2) b.add(x);
List<Integer> onlyA = new ArrayList<>(), onlyB = new ArrayList<>();
for (int x : a) if (!b.contains(x)) onlyA.add(x);
for (int x : b) if (!a.contains(x)) onlyB.add(x);
return List.of(onlyA, onlyB);
}
}
func findDifference(nums1 []int, nums2 []int) [][]int {
a, b := map[int]bool{}, map[int]bool{}
for _, x := range nums1 {
a[x] = true
}
for _, x := range nums2 {
b[x] = true
}
minus := func(x, y map[int]bool) []int {
out := []int{}
for v := range x {
if !y[v] {
out = append(out, v)
}
}
return out
}
return [][]int{minus(a, b), minus(b, a)}
}