# Solving Leetcode Interviews in Seconds with AI: Contains Duplicate II


	# Introduction
	In this blog post, we will explore how to solve the LeetCode problem "219" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like [Chatmagic](https://www.chatmagic.app), we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

	# Problem Statement
	> 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.   Example 1:  Input: nums = [1,2,3,1], k = 3 Output: true  Example 2:  Input: nums = [1,0,1,1], k = 1 Output: true  Example 3:  Input: nums = [1,2,3,1,2,3], k = 2 Output: false    Constraints:  1 <= nums.length <= 105 -109 <= nums[i] <= 109 0 <= k <= 105  

	# Explanation
	Here's a breakdown of the approach, complexity, and the Python code solution:

*   **High-Level Approach:**
    *   Use a hash map (dictionary in Python) to store each number encountered along with its index.
    *   Iterate through the array. For each number, check if it's already in the hash map.
    *   If the number is in the hash map, check if the absolute difference between the current index and the stored index is less than or equal to *k*. If so, return `True`. Otherwise, update the stored index with the current index. If the number is not in the hash map store it with its index.

*   **Complexity:**
    *   Runtime: O(n), where n is the length of the input array.
    *   Storage: O(min(n,k)), as in the worst case we'll need to store n elements.

	
	# Code
	```python
	def containsNearbyDuplicate(nums, k):
    """
    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.

    Args:
        nums (List[int]): The input array of integers.
        k (int): The maximum allowed difference between the indices.

    Returns:
        bool: True if there are two such indices, False otherwise.
    """
    num_map = {}  # Dictionary to store number and its index

    for i, num in enumerate(nums):
        if num in num_map:
            if abs(i - num_map[num]) <= k:
                return True
            else:
                num_map[num] = i  # Update with the new index
        else:
            num_map[num] = i  # Store the number and its index

    return False
	```
			
