Find the Difference of Two Arrays - Problem

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 & Output

Example 1 — Basic Case
$ Input: nums1 = [1,2,3], nums2 = [2,4,6]
Output: [[1,3],[4,6]]
💡 Note: Elements 1 and 3 are in nums1 but not nums2. Elements 4 and 6 are in nums2 but not nums1.
Example 2 — With Duplicates
$ Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]
Output: [[3],[]]
💡 Note: Element 3 is in nums1 but not nums2. All elements of nums2 exist in nums1, so second array is empty.
Example 3 — No Common Elements
$ Input: nums1 = [1,2], nums2 = [3,4]
Output: [[1,2],[3,4]]
💡 Note: No elements are common between arrays, so each array contains all its unique elements.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 1000
  • -1000 ≤ nums1[i], nums2[i] ≤ 1000

Visualization

Tap to expand
Find the Difference of Two Arraysnums1 = [1, 2, 3]123nums2 = [2, 4, 6]246Unique to nums1CommonUnique to nums1CommonUnique to nums2Unique to nums2Common: 2Result: [[1,3], [4,6]]answer[0] = [1,3] (in nums1, not in nums2)answer[1] = [4,6] (in nums2, not in nums1)Find elements unique to each array - like a set difference operation
Understanding the Visualization
1
Input Arrays
nums1 = [1,2,3] and nums2 = [2,4,6]
2
Find Differences
Elements in nums1 not in nums2: [1,3]. Elements in nums2 not in nums1: [4,6]
3
Output
Return [[1,3], [4,6]] as the answer
Key Takeaway
🎯 Key Insight: Use hash sets to convert O(n×m) linear searches into O(1) lookups
Asked in
Amazon 15 Google 12
28.0K Views
Medium Frequency
~15 min Avg. Time
950 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen