Why it works
- Only the nearest earlier copy matters: if any copy is close enough, the latest one is. So the map keeps just the last index of each number.
- A repeat that is too far is not an answer, but it takes over the index: the next copy of the number is measured from it, not from an older one.
- Check first, store after, as in Two Sum: a number never measures the distance to itself.
Complexity
Time O(n): one pass, map lookups are O(1). Memory O(n) for the map; keeping only the last k numbers in a set brings it down to O(k).
nextNow solve it yourself, no hints.
Solve on LeetCode ↗