Contains Duplicate III - Problem

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
  • abs(nums[i] - nums[j]) <= valueDiff

Return true if such pair exists or false otherwise.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,4,7,9], indexDiff = 3, valueDiff = 2
Output: true
💡 Note: Indices 1 and 2: abs(1-2) = 1 ≤ 3 and abs(3-4) = 1 ≤ 2, both conditions satisfied
Example 2 — No Valid Pair
$ Input: nums = [1,5,9,13], indexDiff = 2, valueDiff = 3
Output: false
💡 Note: No pair of indices satisfies both index difference and value difference constraints
Example 3 — Edge Case
$ Input: nums = [1,2], indexDiff = 1, valueDiff = 0
Output: false
💡 Note: abs(1-2) = 1 > 0, so no valid pair exists with valueDiff = 0

Constraints

  • 2 ≤ nums.length ≤ 2 × 104
  • -231 ≤ nums[i] ≤ 231 - 1
  • 1 ≤ indexDiff ≤ nums.length
  • 0 ≤ valueDiff ≤ 231 - 1

Visualization

Tap to expand
Contains Duplicate III - Bucket Sort INPUT Array nums: 1 i=0 3 i=1 4 i=2 7 i=3 9 i=4 Parameters: indexDiff = 3 valueDiff = 2 Find pair (i,j) where: |i - j| <= 3 |nums[i] - nums[j]| <= 2 Valid Pair: (1, 2) nums[1]=3, nums[2]=4 |3-4|=1 <= 2 [OK] ALGORITHM STEPS 1 Calculate Bucket Size w = valueDiff + 1 = 3 2 Assign to Buckets bucket_id = num / w B0 [1] B1 [3,4] B2 [7] B3 [9] 3 Check Same Bucket If bucket exists --> true 4 Check Neighbors Check bucket-1, bucket+1 Processing nums[2]=4: bucket_id = 4/3 = 1 Bucket 1 has 3 already! |4 - 3| = 1 <= 2 Found! Return true FINAL RESULT Output: true Valid Pair Found i = 1 3 j = 2 4 Verification: Index condition: |1 - 2| = 1 <= 3 [OK] Value condition: |3 - 4| = 1 <= 2 [OK] Key Insight: Bucket Sort divides numbers into buckets of size (valueDiff + 1). Elements in the SAME bucket automatically satisfy the value condition. Only need to check current and adjacent buckets. Time: O(n), Space: O(min(n, indexDiff)) - sliding window maintains at most indexDiff buckets. TutorialsPoint - Contains Duplicate III | Bucket Sort Approach
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
85.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen