Contains Duplicate II
Easy
Topics
Given an integer array nums and an integer k, return true if there are two distinct indices i and j such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1
equal values, 3 apart
The shaded cells hold the same value and their indices differ by 3, which is within 3 — so the answer is
true. A repeat on its own is not enough; it has to be a near repeat.Cells are the array values; the small numbers underneath are indices.
Input: nums = [1,2,3,1], k = 3 Output: true Explanation: The two 1s are 3 apart.
Example 2
equal values, 1 apart
Input: nums = [1,0,1,1], k = 1 Output: true Explanation: The 1s at indices 2 and 3 are adjacent.
Example 3
Every repeated value in this array sits further than 2 positions from its twin, so the answer is
false. Note that k = 0 can never succeed, since the two indices have to differ.Input: nums = [1,2,3,1,2,3], k = 2 Output: false Explanation: Every repeated value is 3 apart, which exceeds k.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- 0 <= k <= 10^5
Editorial — intuition, approach, complexity and pitfalls
Intuition
A duplicate on its own is not enough — it has to be a nearby duplicate. So the question is about a window of width k rather than about the array as a whole.
Any pair of equal values more than k apart is irrelevant, which means nothing further back than k positions ever needs remembering.
Approach
- Keep the values of the last
kpositions in a set. - At index
i, if the current value is already in that set then some equal value lies withinkpositions — answertrue. - Otherwise add it, and once the set holds more than
kvalues drop the one ati - k, which has just fallen out of range. - Reaching the end without a hit answers
false. Note thatk = 0permits no pair at all, since the indices must differ.
Walkthrough
nums = [1, 2, 3, 1], k = 3
i=0 window {} add 1 -> {1}
i=1 window {1} add 2 -> {1,2}
i=2 window {1,2} add 3 -> {1,2,3}
i=3 value 1 already in window -> trueComplexity
- Time — O(n): one position per element, with set operations that are constant on average.
- Space — O(min(n, k)): the window never holds more than k values.
Common Pitfalls
- Evicting at the wrong moment is the usual bug: the value leaving the window at index
iis the one ati - k - 1, noti - k. k = 0must answerfalsehowever many duplicates exist, becauseiandjhave to be different.
Full Solution — all languages
class Solution:
def containsNearbyDuplicate(self, hand, k):
if k <= 0:
return False
window = set()
for i, v in enumerate(hand):
if i > k:
window.discard(hand[i - k - 1])
if v in window:
return True
window.add(v)
return Falseimport java.util.*;
class Solution {
public boolean containsNearbyDuplicate(int[] hand, int k) {
if (k <= 0) return false;
Set<Integer> window = new HashSet<>();
for (int i = 0; i < hand.length; i++) {
if (i > k) window.remove(hand[i - k - 1]);
if (window.contains(hand[i])) return true;
window.add(hand[i]);
}
return false;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool containsNearbyDuplicate(vector<int>& hand, int k) {
if (k <= 0) return false;
unordered_set<int> window;
for (int i = 0; i < (int)hand.size(); i++) {
if (i > k) window.erase(hand[i - k - 1]);
if (window.count(hand[i])) return true;
window.insert(hand[i]);
}
return false;
}
};/**
* @param {number[]} hand
* @param {number} k
* @return {boolean}
*/ var containsNearbyDuplicate = function(hand, k) {
if (k <= 0) return false;
const window = new Set();
for (let i = 0; i < hand.length; i++) {
if (i > k) window.delete(hand[i - k - 1]);
if (window.has(hand[i])) return true;
window.add(hand[i]);
}
return false;
};