Leetcode #220: Contains Duplicate III
In this guide, we solve Leetcode #220 Contains Duplicate III in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Bucket Sort, Ordered Set, Sorting, Sliding Window
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
Example
Input: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0
Output: true
Explanation: We can choose (i, j) = (0, 3).
We satisfy the three conditions:
i != j --> 0 != 3
abs(i - j) <= indexDiff --> abs(0 - 3) <= 3
abs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0
Python Solution
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
The time complexity is , where is the length of the array nums. The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.