A sensor glitch shows up as the same reading twice, close together. Write repeat_within(nums: list[int], k: int) -> bool that returns True if two different indexes i, j have nums[i] == nums[j] and |i - j| <= k.
repeat_within([4, 7, 2, 7], 2) # True (the 7s are 2 apart)
repeat_within([4, 7, 2, 4], 2) # False (the 4s are 3 apart)
repeat_within([5, 5], 1) # True
repeat_within([1, 2, 3, 1, 2], 0) # False (k = 0 allows no pairs)
1 <= len(nums) <= 2 * 10^5;0 <= k <= 10^9.- ⭐ Bonus: comparing each reading with the next
k(O(n·k)) still passes; speed tests with 200,000 readings and a largekearn a star in O(n) expected time.
Show hint
keep just the last k readings in a structure with O(1) lookups, adding the newest and dropping the one that falls out.