#219

Contains Duplicate II

Easy Fixed window + HashSet

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Decide whether two equal values exist whose indexes are at most k apart.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: are there two equal values at most k apart?

Why this works: only the last k values matter. Keep them in a set and drop the one that falls out.

Example: [1, 2, 3, 1], k = 3

window {1, 2, 3}next 1 is already in the window → true

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Removing the old element before checking, with an off-by-one that makes the window k - 1 wide.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(k).
Topic: Sliding Window
🎬 Episode 10: video coming soon