BudiBadu Logo

Contains Nearby Duplicate Window

Sliding Window Easy 7 views
Like0

Given an integer array nums and an integer k, determine whether there exist two different indices i and j such that nums[i] == nums[j] and |i - j| <= k.

This can be solved with a sliding-window mindset over index distance. As you scan from left to right, store the latest index of each value in a hash map. When the same value appears again, compare the current index with the previous index. If the distance is within k, return true immediately.

If the full scan ends without finding such a pair, return false.

Example 1:

Input: nums = [1,2,3,1], k = 3

Output: true

Explanation: Value 1 appears at indices 0 and 3; distance is 3, which is allowed.

Example 2:

Input: nums = [1,0,1,1], k = 1

Output: true

Explanation: The last two 1 values are adjacent (distance 1).

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2

Output: false

Explanation: Duplicates exist, but every duplicate pair is farther than 2 apart.

Constraints: 1 <= nums.length <= 10^5, 0 <= k <= 10^5

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