BudiBadu Logo

Contains Nearby Duplicate Window

Sliding Window Easy 22 views
Like0

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

Example 1
Input
nums = [1,2,3,1], k = 3
Output
true
Explanation

Value 1 appears at indices 0 and 3, distance 3.

Example 2
Input
nums = [1,0,1,1], k = 1
Output
true
Explanation

Last two ones are adjacent.

Example 3
Input
nums = [1,2,3,1,2,3], k = 2
Output
false
Explanation

No duplicate appears within distance 2.

Algorithm Flow

Recommendation Algorithm Flow for Contains Nearby Duplicate Window - Budibadu
Recommendation Algorithm Flow for Contains Nearby Duplicate Window - Budibadu

Best Answers

java
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;
    }
}