> For the complete documentation index, see [llms.txt](https://joshualbarb.gitbook.io/leetcode-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://joshualbarb.gitbook.io/leetcode-problems/hash-table/contains-duplicates-ii.md).

# 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)
