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 Arrays INPUT nums1 1 2 3 nums2 2 4 6 Convert to Hash Sets set1 {1, 2, 3} O(1) lookup set2 {2, 4, 6} O(1) lookup [1,2,3], [2,4,6] ALGORITHM STEPS 1 Create Hash Sets Convert both arrays to sets 2 Find diff1 Elements in set1 NOT in set2 3 Find diff2 Elements in set2 NOT in set1 4 Return Result Return [diff1, diff2] Hash Lookup Process 1 in set2? NO --> diff1 2 in set2? YES --> skip 3 in set2? NO --> diff1 4 in set1? NO --> diff2 6 in set1? NO --> diff2 FINAL RESULT answer[0] - Only in nums1 1 3 answer[1] - Only in nums2 4 6 OUTPUT [[1,3],[4,6]] Time: O(n + m) Space: O(n + m) Key Insight: Using Hash Sets provides O(1) average lookup time, making the overall algorithm O(n+m) instead of O(n*m). Sets also automatically handle duplicates, ensuring we return only distinct integers in our result. TutorialsPoint - Find the Difference of Two Arrays | Hash Approach
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