Contains Duplicate II

Easy

Topics
ArrayHash TableSliding Window

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

10213213
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

10011213
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

102132132435
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

  1. Keep the values of the last k positions in a set.
  2. At index i, if the current value is already in that set then some equal value lies within k positions — answer true.
  3. Otherwise add it, and once the set holds more than k values drop the one at i - k, which has just fallen out of range.
  4. Reaching the end without a hit answers false. Note that k = 0 permits 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 -> true

Complexity

  • 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 i is the one at i - k - 1, not i - k.
  • k = 0 must answer false however many duplicates exist, because i and j have 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 False
SensAI
Beta
Tap the mic to stop voice mode