NeetCode #132LC-2215EasyArrays & Hashing
← Back to All Problems

#132 · #2215 · Find the Difference of Two Arrays(找出两数组的不同)

📌 Problem Statement & Constraints

Given two arrays nums1 and nums2, return a list of two lists: the distinct elements of nums1 not in nums2, and the distinct elements of nums2 not in nums1. Constraints: 1 <= nums1.length, nums2.length <= 1000, -1000 <= nums[i] <= 1000.

💡 Core Algorithmic Approaches

  1. Convert both arrays to sets so the output is automatically deduplicated.
  2. The two answers are the set differences s1 - s2 and s2 - s1.
  3. Return them as lists, in either order of elements (the problem accepts any order).
  4. This is the standard set-difference pattern; a two-pointer merge after sorting would also work in O(n log n).

💻 Benchmark Python3 Implementation

class Solution:
    def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
        s1, s2 = set(nums1), set(nums2)
        return [list(s1 - s2), list(s2 - s1)]

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n + m): building the sets and computing the differences are both linear.
💾 Space Complexity
O(n + m) for the sets.

⚠️ Interview Pitfalls & Follow-ups

  • Returning duplicates: the problem requires distinct elements, which the sets guarantee.
  • Using s1 ^ s2 (symmetric difference) for both answers: that merges the two results into one set; you need the two directed differences.
  • Sorting the outputs: not required, and it costs extra time.
  • Nesting the comprehensions incorrectly: [x for x in s1 if x not in s2] works but is O(n * m) if s2 is a list rather than a set.