15% off all plans & roadmaps Use code

See plans

Contains Duplicate II

Updated

TL;DR: You are given an array and a distance k, and must report whether two equal values sit at most k indices apart. Keep the values from the last k positions in a set, and each check becomes a single O(1) membership test.

Problem

You get an integer array nums and an integer k. Decide whether two different indices i and j hold equal values and are no more than k apart, meaning abs(i - j) <= k. Return true if such a pair exists, and false otherwise.

Example 1

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 0 <= k <= 10^5

Constraints that matter

  • n up to 10^5 rules out checking every pair. That is about 5 * 10^9 comparisons in the worst case.
  • k can be as large as n, so the window may hold every value. The memory structure must support fast insert, delete and lookup.
  • Values span about 2 * 10^9 in both directions, so you cannot index an array by value. A hash table is the right tool.
  • k = 0 is allowed. Two distinct indices can never be 0 apart, so the answer is always false.

View on LeetCode

Hints

Hint 1

The question is local.

Hint 2

Compare each index with every later index that lies within k steps.

Solution

Intuition

The question is local. Two equal values count only when they sit close together, so an element never needs to be compared with anything far behind it. The pattern is a sliding window with a condition: the window is the set of recent positions, and its size is capped at k.

Picture a doorman with a clipboard that lists the names of the last k people through the door. The clipboard is the set, each name is a value, and erasing the name from k+1 visits ago is the removal step.

At each index j, ask one question: does the same value appear in the last k positions? If you keep recent values in a structure with fast membership tests, each question costs O(1). That is why a hash-based structure is the natural choice.

There are two ways to store the memory. One records the latest index of every value and compares distances. The other keeps only the values inside the window and evicts the oldest as the window slides. A deque holds the window in arrival order, but it answers membership in O(k), so a set is the better container.

Watch the pattern animation

Worked example

Input: nums = [1, 2, 3, 1, 2, 3], k = 2
Output: false
Explanation: Each pair of equal values is 3 indices apart. The 1s sit at 0 and 3, the 2s at 1 and 4, and the 3s at 2 and 5. Every gap is larger than k = 2, so no pair qualifies.

Approach 1: Brute force

Compare each index with every later index that lies within k steps. For index i, scan j from i + 1 up to i + k, stopping at the array end. If the values match, return true. This follows the definition exactly, but the same neighbours get compared again and again across different i.

Steps

  1. Loop i from 0 to n - 1.
  2. For each i, loop j from i + 1 to min(i + k, n - 1).
  3. If nums[i] equals nums[j], return true.
  4. If both loops finish without a match, return false.

Dry run

Use nums = [1, 2, 3, 1, 2, 3] and k = 2. For i = 0 (value 1), j takes indices 1 and 2 (values 2 and 3), so there is no match. The pair (0, 3) holds two 1s, but j never reaches 3 because the distance is 3.

For i = 1, j takes 2 and 3 (values 3 and 1), and for i = 2, j takes 3 and 4 (values 1 and 2). Neither matches. For i = 3, j takes 4 and 5 (values 2 and 3), and for i = 4, j takes 5 (value 3). Neither matches either.

Index 5 has no later partner. The loops end and the output is false.

Complexity

TimeO(n * min(n, k))
SpaceO(1)

Let n be the array length. The outer loop runs n times. The inner loop runs at most min(k, n - 1 - i) times for each i, so the total number of pairs is bounded by n * min(n, k).

When k is close to n, that is about n^2 / 2, roughly 5 * 10^9 for n = 10^5. The code keeps only a few integer variables, so the extra space is constant.

PythonTested in our runner

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        n = len(nums)
        for i in range(n):
            # Check only the next k positions, or fewer at the end
            for j in range(i + 1, min(i + k, n - 1) + 1):
                if nums[i] == nums[j]:
                    return True
        return False

Approach 2: Last-index hash map

What's slow in the brute force is that a value gets compared with every nearby index, even though only its most recent occurrence matters. If two equal values lie within k of each other, the closest earlier occurrence before j also lies within k. So store the latest index of each value in a map. When index j arrives, compare it with that single stored index, then overwrite the entry with j.

Steps

  1. Create an empty hash map from value to its most recent index.
  2. Walk j from 0 to n - 1.
  3. If nums[j] is in the map and j minus its stored index is at most k, return true.
  4. Store j as the latest index for nums[j], replacing any older entry.
  5. After the loop, return false.

Dry run

Use nums = [1, 2, 3, 1, 2, 3] and k = 2. At j = 0 the map is empty, so it stores {1: 0}. At j = 1 it stores {1: 0, 2: 1}. At j = 2 it stores {1: 0, 2: 1, 3: 2}.

At j = 3 (value 1) the stored index is 0, and 3 - 0 = 3 is greater than 2, so there is no match. The map becomes {1: 3, 2: 1, 3: 2}.

At j = 4 (value 2) the stored index is 1, the distance is 3, and the map becomes {1: 3, 2: 4, 3: 2}. At j = 5 (value 3) the stored index is 2, the distance is 3, and the map becomes {1: 3, 2: 4, 3: 5}. The loop ends and the output is false.

Complexity

TimeO(n)
SpaceO(n)

Let n be the array length. The loop body runs n times, and each map lookup or insert costs O(1) on average, so the total time is O(n) on average. The map holds at most one entry per distinct value, and there are at most n of those, so the space is O(n). This approach ignores k when it stores entries, which is why the final approach reduces the memory cost.

PythonTested in our runner

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        last_index = {}  # value -> most recent index seen
        for j, value in enumerate(nums):
            if value in last_index and j - last_index[value] <= k:
                return True
            last_index[value] = j
        return False

The Variable Size (Condition-Based) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Variable Size (Condition-Based)

Part of Sliding Window

Approach 3: Sliding window setOptimalVariable Size (Condition-Based)

What's slow in the last-index map is that it remembers every value it has ever seen, including values far behind the current index. Only indices from j - k to j - 1 can pair with index j, so keep a set that holds exactly those values.

Before checking index j, remove the value at index j - k - 1, which has fallen out of range. A membership test then answers the question. The set never holds two equal values, because the first repeat returns immediately, so each removal finds its value.

Why it is correct. Before index j is checked, the set holds exactly the values at indices from j - k to j - 1. Any equal pair within distance k has its earlier index still in that range, so the set contains its value when the later index arrives. Older values were removed on time, and the first repeat returns at once, so the set never holds a duplicate and each removal is safe.

Steps

  1. Create an empty set named window.
  2. Walk j from 0 to n - 1.
  3. If j is greater than k, remove nums[j - k - 1] from window.
  4. If nums[j] is in window, return true.
  5. Add nums[j] to window.
  6. After the loop, return false.

Dry run

Use nums = [1, 2, 3, 1, 2, 3] and k = 2. The window must hold the values at indices j - k through j - 1.

jnums[j]removed before checkwindow before checkfoundwindow after adding
01nothing (j is not greater than 2){}no{1}
12nothing{1}no{1, 2}
23nothing{1, 2}no{1, 2, 3}
31nums[0] = 1{2, 3}no{1, 2, 3}
42nums[1] = 2{1, 3}no{1, 2, 3}
53nums[2] = 3{1, 2}no{1, 2, 3}

The loop ends with no match, so the output is false. Each row shows the set holding exactly the last two values, which matches the window size k = 2.

Complexity

TimeO(n)
SpaceO(min(n, k))

Let n be the array length. Each index is added to the set at most once and removed at most once, and each set operation costs O(1) on average, so the time is O(n). Before index j is checked, the set holds the values from at most k indices, and never more than n, so the space is O(min(n, k)). When k is at least n, this matches the O(n) of the last-index map.

PythonTested in our runner

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        window = set()  # values at the last k indices
        for j, value in enumerate(nums):
            if j > k:
                # Index j - k - 1 is now too far back to count
                window.remove(nums[j - k - 1])
            if value in window:
                return True
            window.add(value)
        return False

Common mistakes

  • window.add(nums[j]) placed before the membership check. Every index finds itself and the function returns true at once. Check first, then add.
  • Removing nums[j - k] instead of nums[j - k - 1]. The window then keeps the value at index j - k - 1, which is k + 1 positions back, so pairs at distance k + 1 are accepted. Remove the index that has left the window.
  • Writing j >= k as the removal condition. At j = k the index is -1, which Python reads as the last element through negative indexing. Keep the test as j > k.
  • Using < instead of <= in the distance check of the map version. Pairs exactly k apart are missed, so [1, 2, 1] with k = 2 wrongly returns false.
  • Storing values in a list and testing membership with in or contains. Each test costs O(k), so the whole loop becomes O(n * k) and times out on large inputs. Use a set or a hash map.
  • In the last-index map, returning true whenever a value was seen before and ignoring the distance. On [1, 2, 3, 1] with k = 1, the two 1s are 3 apart, so the answer must be false.

Edge cases

  • k = 0 with any array, such as [1, 1]. Two distinct indices are never 0 apart, so the answer is false.
  • A single element, [5] with k = 1. There is no pair, so the answer is false.
  • Adjacent duplicates, [1, 1] with k = 1. The indices are 1 apart, so the answer is true.
  • Equal values exactly k apart, [1, 2, 1] with k = 2. The answer is true. The same input with k = 1 returns false.
  • Negative values near the bounds, [-1000000000, 1000000000, -1000000000] with k = 2. The answer is true, since hash-based sets and maps handle negative keys without special handling.
  • A large k, such as [1, 2, 3, 1] with k = 100000. The window never evicts early, so the result matches a plain duplicate check, which is true.

Follow-ups interviewers ask

What if the array is sorted?
Sorting the values loses their original indices, so first pair each value with its index and sort by value, then by index. Equal values now sit next to each other in index order. Within each run of equal values, the closest pair is always adjacent, so check the index gap between neighbours. That costs O(n log n) time and O(n) extra space for the pairs.
Can you do it in O(1) extra space?
Not for arbitrary 32-bit values. The sliding window must remember up to k distinct values, and the last-index map must remember every distinct value, so the memory grows with the input. A constant-space answer exists only when the values come from a small known range, where a count array of that size works. Say that tradeoff out loud before you claim anything.
What if the array does not fit in memory?
Stream the values in order and keep a buffer of the last k values, which is exactly the sliding window. Each new value is checked against the buffer, and the oldest value is dropped. The memory cost is O(min(n, k)), independent of how long the stream runs. The last-index map would need one entry per distinct value, which can be far larger.

Contains Duplicate II FAQ

What is the time complexity of Contains Duplicate II?

The hash-based approaches run in O(n) average time, where n is the array length. Each index does one constant-time lookup and one insert or delete. The brute force version takes O(n * min(n, k)) time, which is too slow at n = 10^5.

Why use a sliding window for Contains Duplicate II?

The rule only cares about values within k positions, so the candidates form a window that moves to the right. A set holds exactly the values in that window, and evicting the oldest value keeps it the right size. The window approach also needs less memory than the last-index map.

Can Contains Duplicate II be solved in O(1) extra space?

No, not for arbitrary integers. The window must hold up to k distinct values, so the space grows with min(n, k). A constant-space method works only if the values lie in a small known range, which allows a count array.

Why does a set work when values repeat in the array?

The first repeat inside the window returns true immediately, so the set never holds two equal values. That makes each removal safe, because the value being removed is always present once.

How is Contains Duplicate II different from Contains Duplicate I?

Contains Duplicate I asks only whether any value repeats anywhere, so a plain set of seen values answers it. Contains Duplicate II adds the distance limit k, which forces you to forget values that fall out of range.

Asked at

See which companies ask this — Pro

Practise it