InterviewPrepKit

Home / Coding / Sliding Window

Contains Duplicate II

easy Original ↗
Solving tips
  • Recognize a fixed-size sliding window: you only need to know if a value repeated within the last k positions, answered in O(1) with a hash set.
  • Maintain a set of the last k values; check membership first, add the current value, then evict nums[i-k] when the set exceeds k entries.
  • Alternative: a last-seen-index dict, returning True when i - last_seen[x] <= k.
  • Target O(n) time and O(min(n,k)) space; watch the off-by-one since |i-j|<=k spans k+1 indices, so keep the set at most k values.

Problem

Given an integer array nums and an integer k, decide whether the array contains two distinct indices i and j such that nums[i] == nums[j] and the indices are close together: abs(i - j) <= k. Return True if such a pair exists, False otherwise.

In other words: does any value repeat within a window of k + 1 consecutive positions?

Examples

  • nums = [1, 2, 3, 1], k = 3True — the two 1s sit at indices 0 and 3, and 3 - 0 = 3 <= k.
  • nums = [1, 0, 1, 1], k = 1True — the 1s at indices 2 and 3 are adjacent.
  • nums = [1, 2, 3, 1, 2, 3], k = 2False — every repeated value is exactly 3 apart, which exceeds k = 2.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 0 <= k <= 10^5

Both n and k can be 10^5, so an O(n·k) scan of each index’s neighborhood can hit 10^10 steps — the expected solution is linear.

Think about it first

Hint 1 You only care whether the value at index i appeared anywhere in the previous k positions. What structure answers "have I seen this?" in O(1)?
Hint 2 Maintain a set holding exactly the values inside the last k positions. As the window slides one step right, one value enters and (once the window is full) one value leaves.
Hint 3 For each index i: if nums[i] is already in the set, return True; otherwise add it, and if the set now holds more than k values, remove nums[i - k]. Alternatively, store each value's last-seen index in a dict and compare distances.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.