Determine whether any value appears at least twice in an array with the two occurrences separated by at most k indices.
Problem
You are given an integer array nums and an integer k. Return true if there exist two distinct indices i and j such that:
nums[i] == nums[j]|i - j| <= k
Otherwise, return false.
The goal is to detect whether a duplicate value can be found within a limited index distance.
Input Format
- An integer array
nums - An integer
k
Output Format
- Return
trueif any duplicate pair exists with index difference at mostk - Otherwise return
false
Constraints
0 <= k- The array may contain duplicate values
- Use the index-distance condition
|i - j| <= k
Example 1
Input
nums = [1,2,3,1], k = 3
Output
true
Explanation
The value 1 appears at indices 0 and 3, and the distance is 3, which satisfies the condition.
Example 2
Input
nums = [1,0,1,1], k = 1
Output
true
Explanation
The value 1 appears at indices 2 and 3, and their distance is 1.
Show 1 more example
Example 3
Input
nums = [1,2,3,1,2,3], k = 2
Output
false
Explanation
Duplicates exist, but no equal pair is within distance 2.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.