AlgoInsight

DSA problem

Contains Duplicate III

HardBucket SortPattern: Bucket Sorttop600AmazonGoogleMicrosoftApplePalantir

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, and abs(nums[i] - nums[j]) <= valueDiff. Return true if such a pair exists; otherwise return false.

A brute force checks every pair within the index window, costing O(n * indexDiff). A balanced BST or TreeSet can answer floor/ceiling queries for the current sliding window in O(log indexDiff) per element, giving O(n log indexDiff) total — already strong.

The bucket-sort approach turns the value condition into a hash table lookup. Partition the integer line into buckets of width t + 1 (where t = valueDiff). The bucket containing a number x is x // (t + 1) using floor division (use Math.floor in JS/TS or arithmetic care in Java/C++ to handle negatives correctly — any two numbers within the same bucket differ by at most t). Two numbers within the same bucket are guaranteed close enough in value. Two numbers in adjacent buckets may or may not be close — verify with an explicit difference check.

Maintain a sliding window of size indexDiff over the array. For each nums[i], compute its bucket id; if the bucket already contains an element, return true (same-bucket numbers always satisfy the value diff). Otherwise check the two adjacent buckets and verify their stored value is within t. Insert nums[i] into its bucket. When the window grows past indexDiff, evict the element at index i - indexDiff - 1 from its bucket. The algorithm runs in O(n) amortized time, since each element is inserted and removed exactly once.

Examples

Example 1
Input: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0
Output: true
Explanation: The two 1's are at indices 0 and 3; their index difference is 3 (≤ 3) and their value difference is 0 (≤ 0), so the answer is true.
Example 2
Input: nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3
Output: false
Explanation: Within any window of size 2 the only close-value pairs (the repeated 1, 5, 9) are too far apart in index, so no qualifying pair exists.
Example 3
Input: nums = [-2,3], indexDiff = 1, valueDiff = 5
Output: true
Explanation: The pair (-2, 3) has index difference 1 (≤ 1) and value difference 5 (≤ 5). This case also exercises the negative-number bucketing logic — floor division must put -2 in bucket -1 with bucket width 6, not bucket 0.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bucket-sortsliding-windowhash-tableordered-set

Browse all DSA problems