Contains Duplicate II

Contains Duplicate II

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

LeetCode Problem - 219

import java.util.*;

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        // Create a HashMap to store the last index of each number encountered
        Map<Integer, Integer> mp = new HashMap<>();

        // Iterate through the array
        for (int i=0; i<nums.length; i++){
            // If the number is encountered for the first time, store its index
            if (!mp.containsKey(nums[i])){
                mp.put(nums[i], i);
            } else {
                // If the number is encountered again, calculate the absolute difference of indices
                int ans = Math.abs(mp.get(nums[i]) - i);
                // If the difference is less than or equal to k, return true
                if (ans <= k) {
                    return true;
                }
            }
            // Update the index of the number in the map
            mp.put(nums[i], i);
        }
        // If no duplicates within distance k are found, return false
        return false;
    }
}