Contains Duplicate III Problem
Description
LeetCode Problem 220.
Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
Constraints:
- 1 <= nums.length <= 2 * 10^4
- -2^31 <= nums[i] <= 2^31 - 1
- 0 <= k <= 10^4
- 0 <= t <= 2^31 - 1
Solution
Approach: Buckets of Width t + 1
Checking each element against the k elements before it takes O(n · k) time. Instead, keep the last k values in buckets, so that each check looks at only three buckets.
Bucket b holds the values from b · (t + 1) to b · (t + 1) + t, so a value x goes into bucket floor(x / (t + 1)). Then:
- Two values in the same bucket differ by at most
t, so they are a valid pair. - Two values whose buckets are not neighbors differ by more than
t. - Values in neighboring buckets may or may not be close, so compare them directly.
Walk through nums, keeping only the values from the last k indices in the buckets. For each value x at index i:
- If bucket
balready holds a value, returntrue. - If bucket
b - 1orb + 1holds a value withintofx, returntrue. - Put
xin bucketb. Ifi >= k, removenums[i - k]from its bucket, since it is too far from later indices.
Each bucket holds at most one value, because a second value in it would already have returned true. That is why one value per bucket is enough.
Two details are easy to get wrong:
- Negative numbers. Use floor division. Plain division rounds toward zero in most languages, which would put
-3and3(witht = 3) into the same bucket 0. - Overflow. Values reach -231 and 231 - 1, and
t + 1can be 231. Use 64-bit integers for the bucket id and the differences.
Complexity: O(n) time, where n is the length of nums, and O(min(n, k)) space for the buckets.
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
width = t + 1 # two values in the same bucket differ by at most t
buckets = {} # bucket id -> the value in that bucket, for the last k values only
for i, x in enumerate(nums):
bucket = x // width # floor division, so negative values get their own buckets too
if bucket in buckets:
return True
# A close value can also sit in a neighboring bucket.
if bucket - 1 in buckets and x - buckets[bucket - 1] <= t:
return True
if bucket + 1 in buckets and buckets[bucket + 1] - x <= t:
return True
buckets[bucket] = x
if i >= k:
del buckets[nums[i - k] // width] # nums[i - k] is now too far away
return False