Python coding

A repeat within k positions

Given a list of integers nums and an integer k >= 0, return True if some value appears at two different positions i and j with abs(i - j) <= k, and False otherwise. Copies farther apart than k do not count.

nums may be empty and k may exceed its length. Aim for one pass that keeps at most k values in memory.

Besides the tests, one large input (10,000 distinct values) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • has_close_repeat([1,2,3,1], 3) → true
  • has_close_repeat([1,2,3,1], 2) → false
  • has_close_repeat([7,3,7,3,7], 1) → false
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Fixed-size window: at index i, only the k values just before it can pair with nums[i].

Hint 2

Keep those values in a set. Check the new value, add it, and once the set holds more than k values, remove nums[i - k].

Solution and why it works
pythonO(n) · O(min(n, k))
def has_close_repeat(nums: list[int], k: int) -> bool:
    window = set()                       # the values at most k positions back
    for i, x in enumerate(nums):
        if x in window:
            return True
        window.add(x)
        if len(window) > k:              # the value k steps back leaves the window
            window.remove(nums[i - k])
    return False

The set holds exactly the values up to k positions behind the current one, so a hit is a repeat close enough. Each value enters and leaves once: O(n) time and O(min(n, k)) space, instead of comparing every pair within reach, O(n·k). The trap is forgetting to evict nums[i - k]: an old copy far behind would then count as a close repeat. With k = 0 nothing can match.

Related lab: Sliding window, step by step