Contains Duplicate III (LeetCode 220): Solution and Explanation

Hard
Array
Sliding window
Bucket sort
Hash table
Ordered set

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

  1. Set width = valueDiff + 1 and an empty map from bucket id to value.
  2. For each index i with value x, compute b = floor(x / width), flooring toward negative infinity.
  3. If bucket b is occupied, return true. If bucket b - 1 holds y with x - y <= valueDiff, or bucket b + 1 holds y with y - x <= valueDiff, return true.
  4. Store x in bucket b. If i >= indexDiff, delete the bucket of nums[i - indexDiff], since that index is now too far from everything that follows.
  5. If the loop ends, return false.

Step-by-step example

nums = [1,2,3,1], indexDiff = 3, valueDiff = 0
  1. width = 1, so every value is its own bucket.
  2. i = 0: 1 goes into bucket 1. i = 1: 2 goes into bucket 2; neighbour bucket 1 holds 1, but 2 - 1 = 1 > 0.
  3. i = 2: 3 goes into bucket 3; neighbour bucket 2 holds 2, but 3 - 2 = 1 > 0.
  4. 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 False
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index does a constant number of hash map lookups, one insert and at most one delete.

Space

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 / 2 is 0, which puts -1 and 1 in the same bucket. Floor toward negative infinity instead.
  • Overflow: valueDiff + 1 and differences such as 1e9 - (-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.