Contains Nearby Duplicate Window
In Contains Nearby Duplicate Window, you are checking whether the same number appears again close enough in index distance. You get an integer array nums and an integer k, and the answer is a boolean. Return true only when there are two different indices i and j such that nums[i] == nums[j] and |i - j| <= k. If duplicates exist but the distance is larger than k, that still counts as false.
A practical way to solve this is to scan from left to right while storing the latest index for each value in a hash map. When a value appears, compare current index with its previous index immediately. If the gap is within k, you can stop early and return true. If not, update the stored index and continue.
The judge validates tight-window cases, repeated values that are too far apart, single-element arrays, and k = 0 behavior. Your output must always be a strict boolean result based on index distance, not just whether duplicates exist somewhere in the array.
Examples
Value 1 appears at indices 0 and 3, distance 3.
Last two ones are adjacent.
No duplicate appears within distance 2.
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public boolean contains_nearby_duplicate_window(int[] nums, int k) {
if (k <= 0) return false;
Map<Integer, Integer> last = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (last.containsKey(nums[i]) && i - last.get(nums[i]) <= k) return true;
last.put(nums[i], i);
}
return false;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
