Problem
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.
Algorithm
Sort the index based on the value and then compare the adjacent index.
Code
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
nlen = len(nums)
ids = [x for x in range(nlen)]
ids = [x for _, x in sorted(zip(nums, ids))]
L ,R = 0, 0
while R < nlen:
while L < R and nums[ids[R]] != nums[ids[L]]:
L += 1
while L < R and nums[ids[L+1]] == nums[ids[L]]:
if L < R and ids[L+1]-ids[L] <= k:
return True
L += 1
R += 1
return False