⚡Flashcard Drill➔
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.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

找出两数组的不同

给你两个下标从 0 开始的整数数组 nums1 和 nums2,请你返回一个长度为 2 的列表 answer,其中: answer[0] 是 nums1 中所有 不 存在于 nums2 中的不同整数组成的列表; answer[1] 是 nums2 中所有 不 存在于 nums1 中的不同整数组成的列表。注意:列表中的整数可以按任意顺序返回。约束:1 ≤ nums1.length, nums2.length ≤ 1000;-1000 ≤ nums1[i], nums2[i] ≤ 1000。

核心要点

  • 集合差集(标准解) :把两个数组分别转成集合,答案即 [s1 - s2, s2 - s1] 。
  • 为什么用集合 :题目要求结果中的整数 不同 (去重),集合天然满足;同时集合差集在 C 层实现,效率高。
  • 复杂度 :建集合 O(m + n),差集 O(min(m, n))。
  • 注意返回类型 :题目要求返回列表的列表,因此需要把集合转成 list。

常见陷阱

  • 用 [x for x in nums1 if x not in nums2] :结果未去重(重复元素会多次出现),且 x not in nums2 对列表是 O(n) 查找,整体 O(m · n)。
  • 用对称差集 s1 ^ s2 :那会把两个方向的差异混在一起,无法区分 answer[0] 与 answer[1] 。
  • 忘记转成 list :题目要求返回 list[list[int]] ,直接返回集合不符合类型要求。

参考实现

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)]