Contains Duplicate III — LeetCode 220 Python Solution

HardArrayBucket SortOrdered SetSortingSliding Window
Problem
#220
Reading time
3 min

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 False

Complexity

MeasureComplexity
TimeO(n \times \log k), where n is the length of the array `nums`
SpaceO(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.

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