Find the Difference of Two Arrays - Problem

Given two integer arrays nums1 and nums2, your task is to find the unique elements that exist in one array but not in the other.

Return a list containing exactly two sublists:

  • First sublist: All distinct integers from nums1 that are not present in nums2
  • Second sublist: All distinct integers from nums2 that are not present in nums1

Think of this as finding the "difference" between two sets - what's unique to each array when compared to the other.

Note: The order of elements in the result doesn't matter, and duplicates should be removed from the output.

Input & Output

example_1.py โ€” Basic Difference
$ 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. Element 2 appears in both arrays so it's excluded from both results.
example_2.py โ€” With Duplicates
$ Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]
โ€บ Output: [[3],[]]
๐Ÿ’ก Note: Element 3 appears in nums1 but not nums2. All elements in nums2 (1 and 2) also appear in nums1, so the second result is empty. Duplicates are automatically handled.
example_3.py โ€” No Common Elements
$ Input: nums1 = [1,3], nums2 = [2,4]
โ€บ Output: [[1,3],[2,4]]
๐Ÿ’ก Note: No elements are shared between the arrays, so each array's unique elements form the complete difference sets.

Constraints

  • 1 โ‰ค nums1.length, nums2.length โ‰ค 1000
  • -1000 โ‰ค nums1[i], nums2[i] โ‰ค 1000
  • Both arrays can contain duplicate elements
  • Result should contain only distinct elements

Visualization

Tap to expand
Input Arrays123246nums1 = [1,2,3]nums2 = [2,4,6]14362Set1Set2Result: [1,3]Result: [4,6]
Understanding the Visualization
1
Input Arrays
Start with two arrays that may contain duplicates
2
Convert to Sets
Remove duplicates by converting to hash sets
3
Find Differences
Use set subtraction to find unique elements
4
Return Results
Convert difference sets back to arrays
Key Takeaway
๐ŸŽฏ Key Insight: Hash sets provide O(1) lookup time, making set difference operations extremely efficient for finding unique elements between arrays.
Asked in
Google 23 Amazon 18 Meta 15 Microsoft 12
38.4K Views
Medium Frequency
~15 min Avg. Time
892 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