⚡Flashcard Drill➔
NeetCode #219LC-219EasySliding WindowNC 250
← Back to All Problems

#219 · #219 · Contains Duplicate II(存在重复元素 II)

📌 Problem Statement & Constraints

Given an integer array nums and an integer k, return true if there are two distinct indices i < j such that nums[i] == nums[j] and j - i <= k. Constraints: 1 <= nums.length <= 10^5, -10^9 <= nums[i] <= 10^9, 0 <= k <= 10^5.

💡 Core Algorithmic Approaches

  1. Maintain a sliding window of at most k distinct indices and a set of the values inside it.
  2. If the entering value is already in the set, a duplicate within distance k exists.
  3. Otherwise add it and evict the value that has just fallen out of the window.
  4. The set never needs more than k entries, so the whole scan is O(n).

💻 Benchmark Python3 Implementation

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        window = set()
        for i, x in enumerate(nums):
            if x in window:            # duplicate within distance k
                return True
            window.add(x)
            if len(window) > k:        # evict the element that left the window
                window.discard(nums[i - k])
        return False

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass with O(1) average set operations.
💾 Space Complexity
O(k) for the window.

⚠️ Interview Pitfalls & Follow-ups

  • Using len(window) > k before adding: the eviction must happen after the insertion, so the window size momentarily reaches k + 1.
  • Evicting nums[i - k - 1]: the element leaving the window when the size exceeds k is nums[i - k].
  • Storing a dict of last indices instead of a set: it works, but the set is sufficient and simpler.
  • Returning True for equal values that are farther apart than k: the distance constraint must be enforced by the window size.
⚡
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 Sliding Window Problems

中文速览与面试要点

存在重复元素 II

给你一个整数数组 nums 和一个整数 k,判断数组中是否存在两个 不同的索引 i 和 j,满足 nums[i] == nums[j] 且 abs(i − j) &lt;= k 。如果存在,返回 true;否则,返回 false。约束:1 ≤ nums.length ≤ 10^5;-10^9 ≤ nums[i] ≤ 10^9;0 ≤ k ≤ 10^5。

核心要点

  • 哈希表记录最近下标(标准解) :维护 last (值 → 最近出现的下标)。遍历数组,若当前值已出现过且下标差 ≤ k,则返回 True;否则更新该值的最新下标。
  • 为什么只需记录「最近」下标 :对固定位置 i,若存在更早的相同值 j,则「最近的那个」与 i 的距离最小,最容易满足 ≤ k。因此只需保留最近一次。
  • 窗口视角 :也可以理解为维护一个大小为 k+1 的滑动窗口,检查窗口内是否有重复值。
  • 复杂度 :单次遍历,O(n) 时间、O(n) 空间。

常见陷阱

  • 只记录首次出现下标 :会得到最大的下标差,容易漏掉满足 ≤ k 的情况。必须始终更新为 最近 下标。
  • 判断条件写成 &lt; k :题目要求 &lt;= k 。
  • 用双重循环检查窗口内所有元素 :O(n · k),在 k 很大时退化为 O(n²)。
  • 与 217(存在重复元素)混淆 :217 只要求「存在重复」,无下标距离约束,用集合即可。

参考实现

class Solution:
    def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:
        last = {}                   # 值 -> 最近出现的下标
        for i, x in enumerate(nums):
            if x in last and i - last[x] <= k:
                return True
            last[x] = i             # 始终更新为最新下标
        return False