Contains Duplicate II — LeetCode 219 Python Solution
EasyArrayHash TableSliding Window
- Problem
- #219
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
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 FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.