Contains Duplicate II

Easy#219find a pair

You get an array of numbers and a number k. Find out whether two equal numbers stand at indices no more than k apart. Our example: [7, 3, 9, 7, 4, 9, 4] and k = 2 — yes: the 7s and the 9s are too far apart, but the 4s at indices 4 and 6 are exactly 2 apart.

input
nums: an array of integers; k: an integer, 0 or more.
returns
true if two different indices i and j have nums[i] == nums[j] and |i − j| ≤ k, otherwise false.
constraints
  • 1 ≤ nums.length ≤ 1000
  • −10⁹ ≤ nums[i] ≤ 10⁹
  • 0 ≤ k ≤ 1000
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {boolean}
 */
function containsNearbyDuplicate(nums, k) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more hash map problems

Pattern “Hash map” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.