Skip to main content
Back to problems
Leetcode
Easy
Arrays
Hash Maps
Sets
Amazon
Contains Duplicate II

Determine whether any value appears at least twice in an array with the two occurrences separated by at most k indices.

Acceptance 75%
Problem Statement

Problem

You are given an integer array nums and an integer k. Return true if there exist two distinct indices i and j such that:

  • nums[i] == nums[j]
  • |i - j| <= k

Otherwise, return false.

The goal is to detect whether a duplicate value can be found within a limited index distance.

Input Format

  • An integer array nums
  • An integer k

Output Format

  • Return true if any duplicate pair exists with index difference at most k
  • Otherwise return false

Constraints

  • 0 <= k
  • The array may contain duplicate values
  • Use the index-distance condition |i - j| <= k
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,2,3,1], k = 3

Output

true

Explanation

The value 1 appears at indices 0 and 3, and the distance is 3, which satisfies the condition.

Example 2

Input

nums = [1,0,1,1], k = 1

Output

true

Explanation

The value 1 appears at indices 2 and 3, and their distance is 1.

Show 1 more example

Example 3

Input

nums = [1,2,3,1,2,3], k = 2

Output

false

Explanation

Duplicates exist, but no equal pair is within distance 2.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.