AlgoMaster Logo

Contains Duplicate II

nums=[1, 2, 3, 1],k=3
1class Solution {
2    public boolean containsNearbyDuplicate(int[] nums, int k) {
3        HashMap<Integer, Integer> map = new HashMap<>();
4
5        for (int i = 0; i < nums.length; i++) {
6            // Check if number exists and distance <= k
7            if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
8                return true;
9            }
10            // Update latest index of current number
11            map.put(nums[i], i);
12        }
13
14        return false;
15    }
16}
0 / 15
12310123Hash Map (num → index)k = 3
DSA Animation | AlgoMaster.io | AlgoMaster.io