Contains Duplicate II
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that:
• nums[i] == nums[j]
• abs(i - j) <= k
Otherwise, return false.
Example 1
Input
5 1 2 3 1 4 3
Output
true
Explanation
The value 1 appears at indices 0 and 3, and the distance between them is 3, which is less than or equal to k.
Example 2
Input
6 1 2 3 1 2 3 2
Output
false
Explanation
Although duplicate values exist, the distance between every pair of equal values is greater than k.
Constraints
Hints:
Hint 1
Use a hash map to store the most recent index of each element.
Hint 2
If the current element has been seen before and the difference between the current index and its previous index is less than or equal to k, return true.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 6, 2026
Last updated
Aug 7, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output