Contains Duplicate III — LeetCode 220 Python Solution
HardArrayBucket SortOrdered SetSortingSliding Window
- Problem
- #220
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an integer array nums and two integers indexDiff and valueDiff. Find a pair of indices (i, j) such that: i != j, abs(i - j) <= indexDiff.
Example
- Input
- nums = [1,2,3,1], indexDiff = 3, valueDiff = 0
- Output
- true
- Explanation
- We can choose (i, j) = (0, 3).
Python solution
Python
class Solution:
def containsNearbyAlmostDuplicate(
self, nums: List[int], indexDiff: int, valueDiff: int
) -> bool:
s = SortedSet()
for i, v in enumerate(nums):
j = s.bisect_left(v - valueDiff)
if j < len(s) and s[j] <= v + valueDiff:
return True
s.add(v)
if i >= indexDiff:
s.remove(nums[i - indexDiff])
return FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log k), where n is the length of the array `nums` |
| Space | O(1) to O(n) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 220. Contains Duplicate III 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
Frequently asked questions
- How hard is LeetCode 220. Contains Duplicate III?
- LeetCode 220. Contains Duplicate III is rated Hard on LeetCode.
- What topics does LeetCode 220. Contains Duplicate III cover?
- LeetCode 220. Contains Duplicate III is tagged Array, Bucket Sort, Ordered Set, Sorting and Sliding Window on LeetCode.