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

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:

        # 1. Inputs and outputs:
        # Inputs:
        #   nums -> list of integers to check for duplicates
        #   k -> conditional int for checking abs value of i-j
        # Outputs:
        #   res -> boolean true if there exists and answer

        # 2. Edge cases, boundaries and other tests:
        # Check if the list if empty
        # Check if the list has 1 entry
        # Check if the list has 2 entries
        # Check if the list has all the same number
        # Check if k is valid
        # Check some random test cases with varying patterns
        # Add some test cases using chatgpt

        # 3: Algorithm:
        # 2 ways come to mind:

        # Way 1:
        # Initialize a dictionary to keep track of numbers with their indices
        # If the number isnt in, create a new value with its index
        # If its there, compare to see if the index is valid
        #   If yes, return true
        # Else, continue

        # Way 2:
        # Sort the list with indices
        # Use two pointers to run through all tuples
        # Check validity, and update pointers

        # 4. Code: (way 1)

        n = len(nums)

        if n == 1 or 0: return False

        d = {}

        for i in range(n):
            if nums[i] not in d:
                d[nums[i]] = i

            else:
                if abs(i - d[nums[i]]) <= k: return True
                d[nums[i]] = i
        return False

29481