Contains Duplicate III (LeetCode 220): Solution and Explanation
Decide whether two indices at most indexDiff apart hold values at most valueDiff apart. Bucketing values by floor(x / (valueDiff + 1)) and keeping only the last indexDiff values in the buckets answers it in one linear pass.
Intuition
The index condition is a sliding window: when we stand at i, the only partners that matter are the previous indexDiff values.
The value condition asks whether the window holds anything within valueDiff of x. Cut the number line into buckets of width valueDiff + 1. Two values in the same bucket are at most valueDiff apart, so if a bucket is ever asked to hold a second value we already have the answer.
A value close to x cannot be two buckets away, because that gap is more than valueDiff. So each step looks at three buckets only: b, b - 1 and b + 1, and the neighbours need one explicit distance check.
Approach: Bucket sliding window
- Set
width = valueDiff + 1and an empty map from bucket id to value. - For each index
iwith valuex, computeb = floor(x / width), flooring toward negative infinity. - If bucket
bis occupied, return true. If bucketb - 1holdsywithx - y <= valueDiff, or bucketb + 1holdsywithy - x <= valueDiff, return true. - Store
xin bucketb. Ifi >= indexDiff, delete the bucket ofnums[i - indexDiff], since that index is now too far from everything that follows. - If the loop ends, return false.
Step-by-step example
nums = [1,2,3,1], indexDiff = 3, valueDiff = 0
- width = 1, so every value is its own bucket.
- i = 0: 1 goes into bucket 1. i = 1: 2 goes into bucket 2; neighbour bucket 1 holds 1, but 2 - 1 = 1 > 0.
- i = 2: 3 goes into bucket 3; neighbour bucket 2 holds 2, but 3 - 2 = 1 > 0.
- i = 3: 1 maps to bucket 1, which still holds the 1 from index 0 (only 3 indices back). Return true.
Code: Python, Java, C++
1class Solution:
2 def containsNearbyAlmostDuplicate(self, nums: List[int], indexDiff: int, valueDiff: int) -> bool:
3 width = valueDiff + 1
4 buckets = {}
5 for i, x in enumerate(nums):
6 b = x // width
7 if b in buckets:
8 return True
9 if b - 1 in buckets and x - buckets[b - 1] <= valueDiff:
10 return True
11 if b + 1 in buckets and buckets[b + 1] - x <= valueDiff:
12 return True
13 buckets[b] = x
14 if i >= indexDiff:
15 del buckets[nums[i - indexDiff] // width]
16 return False1class Solution {
2 public boolean containsNearbyAlmostDuplicate(int[] nums, int indexDiff, int valueDiff) {
3 long width = (long) valueDiff + 1;
4 Map<Long, Long> buckets = new HashMap<>();
5 for (int i = 0; i < nums.length; i++) {
6 long x = nums[i];
7 long b = Math.floorDiv(x, width);
8 if (buckets.containsKey(b)) {
9 return true;
10 }
11 if (buckets.containsKey(b - 1) && x - buckets.get(b - 1) <= valueDiff) {
12 return true;
13 }
14 if (buckets.containsKey(b + 1) && buckets.get(b + 1) - x <= valueDiff) {
15 return true;
16 }
17 buckets.put(b, x);
18 if (i >= indexDiff) {
19 buckets.remove(Math.floorDiv((long) nums[i - indexDiff], width));
20 }
21 }
22 return false;
23 }
24}1class Solution {
2public:
3 bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {
4 long long width = (long long)valueDiff + 1;
5 unordered_map<long long, long long> buckets;
6 for (int i = 0; i < (int)nums.size(); i++) {
7 long long x = nums[i];
8 long long b = bucketOf(x, width);
9 if (buckets.count(b)) {
10 return true;
11 }
12 if (buckets.count(b - 1) && x - buckets[b - 1] <= valueDiff) {
13 return true;
14 }
15 if (buckets.count(b + 1) && buckets[b + 1] - x <= valueDiff) {
16 return true;
17 }
18 buckets[b] = x;
19 if (i >= indexDiff) {
20 buckets.erase(bucketOf(nums[i - indexDiff], width));
21 }
22 }
23 return false;
24 }
25
26private:
27 long long bucketOf(long long x, long long width) {
28 return x >= 0 ? x / width : (x + 1) / width - 1;
29 }
30};Time and space complexity
O(n)
Each index does a constant number of hash map lookups, one insert and at most one delete.
O(min(n, indexDiff))
The map holds at most one bucket per index in the window.
Other approaches
Ordered set window (time O(n log k), space O(k))
Keep the last indexDiff values in a balanced BST or TreeSet and ask for the smallest value at least x - valueDiff. Simple to reason about and common in Java and C++ answers.
Brute force (time O(n * k), space O(1))
Compare every index with the indexDiff indices before it. Correct, but quadratic when indexDiff is large.
Common mistakes
- Using truncating division for negative values. In Java, C++, C# and Go
-1 / 2is 0, which puts -1 and 1 in the same bucket. Floor toward negative infinity instead. - Overflow:
valueDiff + 1and differences such as1e9 - (-1e9)do not fit in 32 bits. Use 64-bit integers for bucket ids and differences. - Skipping the neighbour buckets. Values 4 and 5 with valueDiff = 1 land in different buckets yet are close enough.
- Removing the old value before checking, or removing at the wrong index, which shrinks or grows the window by one.
Frequently asked questions
Why is the bucket width valueDiff + 1 and not valueDiff?
A bucket of width w holds values whose difference is at most w - 1. Width valueDiff + 1 makes any two values in one bucket a valid pair, and it also works when valueDiff is 0.
Why can each bucket hold just one value?
As soon as a second value arrives in an occupied bucket, the two values are close enough and the window guarantees the indices are too, so we return true immediately.
Why do neighbour buckets need an explicit check but the same bucket does not?
Values in adjacent buckets can be anywhere from 1 to 2 * valueDiff + 1 apart, so we must compare them. Values in the same bucket are always within valueDiff.
What is the time and space complexity?
O(n) time and O(min(n, indexDiff)) space, versus O(n log k) for the ordered set approach.