def containsNearbyDuplicate(self, nums, k):
dic = {}
for i, v in enumerate(nums):
if v in dic and i  dic[v] <= k:
return True
dic[v] = i
return False
Python concise solution with dictionary.

I keep a window of size k, but get "Time Limit Exceeded":
def contains_near_by_duplicate1(self, nums, k): if not nums or k <= 0: return False num_dict = {} for index, value in enumerate(nums): if value in num_dict.values(): return True else: num_dict[index] = value if index > k: del num_dict[indexk1] return False

@nkcoder
The reason that you're getting TLE is because you're searching for a value in a list in the line:if value in num_dict.values()
which takesO(n)
. OP avoids that by using the value as a key of the dictionary. Thus, the value can be searched in the dictionary inO(1)
time.

@ikelber Can I ask you a stupid question? what is OP??
And I think the original solution also got TLE

I used this method to keep a k length window, but meet Time Limited Exceeded problem, someone can explain that? Thanks.
if len(nums)==0 or k<=0: return False dic = {} for index,value in enumerate(nums): if index>k: del dic[indexk1] if value in dic.values(): return True else: dic[index] = value return False

@nkcoder I tried your method but meet TLE problem. Also you should move the update of dictionary to the first part of for loop.