⚡Flashcard Drill➔
NeetCode #2LC-217EasyArrays & HashingBlind 75NC 150NC 250
← Back to All Problems

#2 · #217 · Contains Duplicate(存在重复元素)

📌 Problem Statement & Constraints

Given an integer array nums, return true if any value appears at least twice, and false if every element is distinct. Constraints: 1 <= nums.length <= 10^5, -10^9 <= nums[i] <= 10^9.

💡 Core Algorithmic Approaches

  1. Walk the array once and keep a hash set of values already seen.
  2. For each element, test membership first: if it is already in the set, we have a duplicate, so return true immediately.
  3. Otherwise add it and continue. If the loop finishes, every value was unique, so return false.
  4. The early return is what keeps the average case cheap; there is no need to finish the scan once a duplicate is found.

💻 Benchmark Python3 Implementation

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        seen = set()
        for x in nums:
            if x in seen:          # second sighting -> duplicate
                return True
            seen.add(x)
        return False


# One-liner equivalent: build the set, compare its size
class Solution2:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(set(nums)) != len(nums)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n) expected time: one pass, with O(1) average-cost hash lookups and insertions. The theoretical worst case is O(n^2) if the hash function degenerates, which Python's randomized string/int hashing makes practically unreachable.
💾 Space Complexity
O(n) for the set in the worst case (all elements distinct). A sort-based solution would use O(1) extra space but cost O(n log n) time, so the set wins on time and loses on space.

⚠️ Interview Pitfalls & Follow-ups

  • Sorting first: nums.sort() then comparing neighbours is O(n log n) and mutates the input. Correct, but strictly worse than the hash-set pass.
  • Using a list instead of a set for seen: membership becomes O(n), turning the whole algorithm into O(n^2).
  • Thinking the set always needs O(n) memory: it does in the worst case, but the early return means a duplicate-heavy input stops almost immediately.
  • Overflow worries: values reach 1e9, but that is irrelevant for hashing; no arithmetic is performed.
⚡
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

中文速览与面试要点

存在重复元素

给你一个整数数组 nums。如果任一值在数组中出现至少两次,返回 true;如果数组中每个元素互不相同,返回 false。约束:1 ≤ nums.length ≤ 10^5;-10^9 ≤ nums[i] ≤ 10^9。

核心要点

  • 哈希集合一次遍历(最优) :维护集合 seen,遍历 nums,若 x 已在 seen 中立即返回 True,否则把 x 加入 seen。遍历结束仍未命中则返回 False。
  • 为什么不能只看相邻 :题目要求的是「任意两个相同」,与位置无关,因此不需要排序;一旦排序就退化为 O(n log n)。
  • 等价一行写法 : len(set(nums)) != len(nums) 。语义完全一致,且 set 构造是 C 层循环,常数比手写 for 更小。
  • 早期退出的价值 :有重复时平均只需扫描到第一个重复对即可返回,实测随机数据下平均比较次数远小于 n。

常见陷阱

  • 以为 排序法更优 :排序是 O(n log n) 且需要 O(n) 拷贝才能不破坏入参,只有在「数组已近乎有序」或「内存极度受限」时才值得考虑。
  • 把 哈希集合与哈希表 混为一谈:本题只需要「存在性」,用 set 而非 dict;用 dict 存计数会多耗内存且无收益。
  • 忽略 空数组与单元素 边界:长度 1 必然返回 False,代码虽天然正确,但面试时主动提一句能体现边界意识。
  • 被追问 内存不够怎么办 时答不上来:可用位图(元素范围有限时)、布隆过滤器(允许误判)、或外排(external sort)分块处理。

参考实现

class Solution:
    def containsDuplicate(self, nums: list[int]) -> bool:
        seen = set()
        for x in nums:
            if x in seen:
                return True
            seen.add(x)
        return False

# 工程上更常用的等价写法(常数更小):
# return len(set(nums)) != len(nums)