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
- Maintain a sliding window of at most
kdistinct indices and a set of the values inside it. - If the entering value is already in the set, a duplicate within distance
kexists. - Otherwise add it and evict the value that has just fallen out of the window.
- The set never needs more than
kentries, 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) > kbefore adding: the eviction must happen after the insertion, so the window size momentarily reachesk + 1. - Evicting
nums[i - k - 1]: the element leaving the window when the size exceedskisnums[i - k]. - Storing a dict of last indices instead of a set: it works, but the set is sufficient and simpler.
- Returning
Truefor equal values that are farther apart thank: 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.
🧩 Related Sliding Window Problems
#220 · #121Best Time to Buy and Sell Stock#221 · #2379Minimum Recolors to Get K Consecutive Black Blocks#222 · #1984Minimum Difference Between Highest and Lowest of K Scores#223 · #1343Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold#224 · #1052Grumpy Bookstore Owner#225 · #487Max Consecutive Ones II
中文速览与面试要点
存在重复元素 II
给你一个整数数组 nums 和一个整数 k,判断数组中是否存在两个 不同的索引 i 和 j,满足 nums[i] == nums[j] 且 abs(i − j) <= 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 的情况。必须始终更新为 最近 下标。
- 判断条件写成 < k :题目要求 <= 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