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 | def func(nums,k): |
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 | def func(nums,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.




