Problem 357989 · easy · Level 03 Linear Management & Searching

Repeat Within Distance

sliding window · hash set · fixed-size window

A turnstile records the badge id of every entry in badges. Security flags a badge if it is scanned twice within k entries of itself, i.e. there are indices i < j with badges[i] == badges[j] and j - i <= k. Return True if any badge is flagged, otherwise False.

Examples

Input:  badges = [1, 2, 3, 1], k = 3
Output: True
Explanation: badge 1 appears at indices 0 and 3, and 3 - 0 <= 3.

Input:  badges = [1, 2, 3, 1, 2, 3], k = 2
Output: False

Constraints

  • 0 <= len(badges) <= 10**5
  • 0 <= k <= 10**5
  • -10**9 <= badges[i] <= 10**9
  • Target complexity: O(n) time; comparing every pair within distance k is too slow for the largest tests.

Goals

  • Maintain a set of the last k values as the window moves
  • Return early as soon as a repeat is detected
Starting Python…