CodingNodes / Arrays & Hashing / Contains Duplicate II System design Space play · ←→ step · R restart

Problem

You get an array of integers nums and a distance limit k.

Decide whether two different positions i and j exist with nums[i] == nums[j] and |i − j| ≤ k. Return true if so, otherwise false.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • −10⁹ ≤ nums[i] ≤ 10⁹
  • 0 ≤ k ≤ 10⁵

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: One pass over nums, and each map lookup or insert is O(1) on average.

Space: The map can hold one entry per distinct value, up to n entries.

Remember the last index of every value. When a value shows up again, compare the gap to the previous index with k. Then overwrite the entry, because the newest index is always the closest.