<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,1], k = 3
<strong>Output:</strong> true
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,0,1,1], k = 1
<strong>Output:</strong> true
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2
<strong>Output:</strong> false
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
	<li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li>
</ul>

'''
Notes:
- it is not sorted
- the distance of index needs to be below k
- naive way: for each integer, try to move k to find it. O((n-k)*k)
- sort with index, then find the pair that has different less than k or move on: time: O(nlogn), but cost space O(n)

Approach: go with the sort solution
'''
class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        if len(nums) == 1:
            return False

        val_index_list = []

        for index, val in enumerate(nums):
            val_index_list.append((val, index))
        
        val_index_list.sort()

        prev_val = val_index_list[0][0]
        prev_index = val_index_list[0][1]
        for i in range(1, len(val_index_list)):
            if val_index_list[i][0] == prev_val:
                if val_index_list[i][1] - prev_index <= k:
                    return True
            prev_val = val_index_list[i][0]
            prev_index = val_index_list[i][1]
        return False
31138