Skip to content
Problem 219 · LeetCode 219(opens in a new tab)

Contains Duplicate II

EasyArrays

You are given a list of whole numbers, nums, and a whole number k. Decide whether some value appears twice at positions that are close together: two different indices i and j with the same value and with i and j at most k apart.

Return true if such a pair exists, and false otherwise.

Example 1

Input:  nums = [5, 1, 8, 5, 8], k = 2
Output: true
Why:    the 8s at indices 2 and 4 are 2 apart
2 more examples and the constraints

Example 2

Input:  nums = [2, 5, 2, 5], k = 1
Output: false
Why:    each repeat is 2 apart, more than 1

Example 3

Input:  nums = [9, 9], k = 0
Output: false
Why:    a gap of 0 would need the same index twice

Constraints

  • 1 ≤ length of nums ≤ 100,000
  • Every number is between −1,000,000,000 and 1,000,000,000
  • 0 ≤ k ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check the next k numbersO(n·k)
  2. Map of last positionsO(n)
  3. Sliding window setO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbers, k = 100,000Verdict
Check the next k numbersO(n·k)
Mention it, then move on
Map of last positionsO(n)
Passes; memory grows with n
Sliding window setO(n)
Best; at most k + 1 values kept

n = how many numbers are in the list, k = the largest allowed gap.

Edge cases to test

  • k = 0. No pair can be 0 apart, so the answer is always false.
  • k bigger than the list. Then any repeat at all counts; the window never needs trimming.
  • Gap exactly k. [7, 1, 2, 3, 7] with k = 4 is true; with k = 3 it is false.
  • Repeats that are too far. A value can appear many times and still give false if every copy is more than k from the next.

Common mistakes

  • Trimming the window before the check, so a twin exactly k back is dropped too early.
  • Keeping the first index of each value instead of the latest one in the map approach.
  • Using < instead of <= when comparing the gap with k.

How to talk through it

  1. 1Clarify. Is the gap at most k or strictly less? Can k be 0 or bigger than the list?
  2. 2Give the brute force. Check the next k numbers after each one: O(n·k), too slow when k is large.
  3. 3Remember positions. A map from value to its last index answers each check in O(1).
  4. 4Shrink to a window. Only the last k values matter, so a set of that size is enough. Say when you add and when you drop.
  5. 5Test out loud. Run k = 0, a gap of exactly k and a gap of k + 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?