leetcode-study

219. Contains Duplicate II

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        """
        Determine if the array 'nums' contains two distinct indices i and j such that
        nums[i] == nums[j] and the absolute difference between i and j is at most k.
        
        Parameters:
            nums (List[int]): The list of integers to check for duplicates.
            k (int): The maximum allowed index difference between duplicate elements.
        
        Returns:
            bool: True if such a duplicate pair exists, otherwise False.
        """
        # Dictionary to store the most recent index of each element.
        last_seen = {}
        
        # Iterate over the list with enumeration to get both index and value.
        for i, num in enumerate(nums):
            # Check if current number has been seen before and if the difference
            # between the current index and the last seen index is within k.
            if num in last_seen:
                # If the index difference is within the given range k, return True.
                if i - last_seen[num] <= k:
                    return True
            # Update the last seen index for the current number.
            last_seen[num] = i
        
        # If no nearby duplicates were found, return False.
        return False

Summary of Techniques and Approaches: