progress

~/problems / Sliding window

Contains Duplicate II

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

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 large k earn 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.

Topic: Sliding window. Grow right, shrink left while invalid; monotonic deque for window max/min.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc