LeetCode 219: Contains Duplicate II

Problem Description

Explanation

To solve this problem, we can iterate through the array and keep track of the indices of each number we encounter using a HashMap. For each number, if it already exists in the HashMap, we check if the absolute difference of the current index and the previous index of that number is less than or equal to k. If it is, we return true. If we finish iterating through the array without finding any such pair, we return false.

  • Time complexity: O(n) where n is the number of elements in the array.
  • Space complexity: O(min(n, k)) where n is the number of elements in the array and k is the value of k.

Solutions

import java.util.HashMap;

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
                return true;
            }
            map.put(nums[i], i);
        }
        
        return false;
    }
}

Loading editor...