# Contains Duplicates II

## Problem

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that **nums\[i] = nums\[j]** and the **absolute** difference between i and j is at most k.

![](/files/-MR1iNt88sC-oS3mLaAb)

### Thought Process

* Using a dictionary, linearly go through the array and check if the number already exists in the dictionary. If it does, the the abosulte difference between their indexes HOWEVER if the difference is more than k update the index of that number in the dictionary.

## Solution

```
class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        d = {}
        
        for i in range(len(nums)):
            if nums[i] in d:
                if abs(i - d[nums[i]]) <= k:
                    return True
            d[nums[i]] = i
        return False
                
```

## Time Complexity

* **Time:** O(n)
* **Space:** O(n)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://joshualbarb.gitbook.io/leetcode-problems/hash-table/contains-duplicates-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
