A duplicate by itself isn’t enough here. The question asks whether there are two different positions holding the same number, with at most k places between them.

I spent longer on this than I expected. I knew checking every possible pair would be slow. Then I started thinking about groups of k+1 elements, and what to do about a duplicate that showed up after I’d moved on to the next group. I was making it harder than it needed to be.

The official solution gave me a better question to ask at each position: have I seen this value in the last k positions? Here’s my first attempt at keeping that little window in a Python list:

1
2
3
4
5
6
7
8
9
10
11
12
def func(nums,k):
a = []
for i in nums:
if((i not in a) and (len(a)<k)):
a.append(i)
elif((i not in a) and len(a)==k):
a.pop(0)
a.append(i)
elif(i in a):
return True
return False

I thought I was done because I’d only looped over the input once. But i in a can search all the way through the window on every pass, and popping the first item makes Python shift the rest. The judge timed me out again.

Then I found this dictionary version. It was short enough to fit on a postcard and took me ages to read:

1
2
3
4
5
def func(nums,k):
r, d = k + 1, {}
for i, n in enumerate(nums):# i is the index and n is the value
r, d[n] = min(r, i - d.get(n, -k - 1)), i
return r <= k

The trick is that d[n] holds the most recent index for the value n. Say I last saw it at 4 and I’m now at 7. The distance is 3. Any earlier occurrence is even farther away, so the most recent one is all I need. Calculate the gap, keep the smallest one in r, and then update the dictionary with the new index. The two assignments share a line, but the distance is calculated from the old index.

If the smallest gap is at most k, we’ve found our pair.