Find the Difference of Two Arrays
Easy · Arrays & Hashing · Array · Hash Table
Problem
You are given two integer arrays, nums1 and nums2. Return a list answer of two lists:
- answer[0]: the distinct values of nums1 that do not appear anywhere in nums2;
- answer[1]: the distinct values of nums2 that do not appear anywhere in nums1.
Each value is listed once even if it repeats, and the values inside each list may come in any order.
Examples
Input: nums1 = [1, 2, 3], nums2 = [2, 4, 6] Output: [[1, 3], [4, 6]]
2 is in both arrays; 1 and 3 only in nums1; 4 and 6 only in nums2.
Input: nums1 = [1, 2, 3, 3], nums2 = [1, 1, 2, 2] Output: [[3], []]
3 appears twice in nums1 but is listed once; every value of nums2 is also in nums1.
Input: nums1 = [-5, 0], nums2 = [0, 8, 8] Output: [[-5], [8]]
Constraints
- 1 <= nums1.length, nums2.length <= 1000
- -1000 <= nums1[i], nums2[i] <= 1000
Approaches
- Scan the other array for each value — time O(n · m), space O(n + m)
Follow-up
What if repeated values must be counted, so three copies against one leave two extra? And with more than two arrays, how do you find the values that only one array has without comparing every pair?
Related problems
Start free on Cariara · Coding problems · System design studio