EasyNo. 0219
Contains Duplicate II — LeetCode 219 Python Solution
- Pattern
- Sliding Window
- Topics
- Array, Hash Table, Sliding Window
- On a study list
- Top Interview 150
- 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
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
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0217 | Contains Duplicate | Easy |
| 0480 | Sliding Window Median | Hard |
| 0594 | Longest Harmonious Subsequence | Easy |
| 0632 | Smallest Range Covering Elements from K Lists | Hard |
| 0904 | Fruit Into Baskets | Medium |
| 0930 | Binary Subarrays With Sum | Medium |
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.