ExamAdda Logo

Contains Duplicate II

Easy

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

1 ≤ nums.length ≤ 10^5
-10^9 ≤ nums[i] ≤ 10^9
0 ≤ k ≤ 10^5

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

ExamAdda Technical Review Team

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.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output