Contains Duplicate II — LeetCode 219 Python Solution

EasyArrayHash TableSliding Window
Problem
#219
Reading time
2 min

The problem

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

Example

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

Python solution

Python
class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        d = {}
        for i, x in enumerate(nums):
            if x in d and i - d[x] <= k:
                return True
            d[x] = i
        return False

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 219. Contains Duplicate II is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 219. Contains Duplicate II?
LeetCode 219. Contains Duplicate II is rated Easy on LeetCode.
What is the time complexity of LeetCode 219. Contains Duplicate II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 219. Contains Duplicate II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 219. Contains Duplicate II cover?
LeetCode 219. Contains Duplicate II is tagged Array, Hash Table and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview