Contains Duplicate II
Problem Statement
You are given an integer array nums and an integer k.
Return true if there are two different indices i and j with the same value (nums[i] == nums[j]) that are at most k apart (|i − j| ≤ k). Otherwise return false.
An integer array nums and an integer k.
true if some value repeats within distance k, else false.
The two 1s are at indices 0 and 3. They are 3 apart, and 3 ≤ 3.
The 1s at indices 2 and 3 are 1 apart.
Every value repeats, but each repeat is exactly 3 apart, which is more than 2.
- • 1 ≤ nums.length ≤ 10^5
- • −10^9 ≤ nums[i] ≤ 10^9
- • 0 ≤ k ≤ 10^5
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each i, compare with the next k elements
For each x, compare with the last index of x; then overwrite it
A useful partner for nums[i] must be within k steps. So for each i, look at nums[i+1] … nums[i+k] (stopping at the end of the array) and return true on any equal value.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Arrays & Hashing translate into production architectures and low-level memory mechanics.