Contains Duplicate III - Problem
You're given an integer array nums and two integers indexDiff and valueDiff. Your task is to find if there exists a pair of indices (i, j) that satisfy all of the following conditions:
i != j(different indices)abs(i - j) <= indexDiff(indices are close enough)abs(nums[i] - nums[j]) <= valueDiff(values are similar enough)
Return true if such a pair exists, false otherwise.
Example: If nums = [1,2,3,1], indexDiff = 3, and valueDiff = 0, we need to find two identical values within 3 positions of each other. The answer is true because nums[0] = nums[3] = 1 and abs(0-3) = 3 <= 3.
Input & Output
example_1.py โ Basic Match
$
Input:
nums = [1,2,3,1], indexDiff = 3, valueDiff = 0
โบ
Output:
true
๐ก Note:
We find indices i=0 and j=3 where nums[0]=1 and nums[3]=1. The constraints are satisfied: |0-3|=3 โค 3 and |1-1|=0 โค 0.
example_2.py โ Value Difference
$
Input:
nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3
โบ
Output:
false
๐ก Note:
No two elements within indexDiff=2 positions have a value difference โค 3. For example, indices 0,1: |1-5|=4 > 3.
example_3.py โ Edge Case
$
Input:
nums = [1,3,1], indexDiff = 1, valueDiff = 1
โบ
Output:
false
๐ก Note:
Adjacent pairs: (1,3) at indices 0,1 has |1-3|=2 > 1, and (3,1) at indices 1,2 has |3-1|=2 > 1. No valid pair exists.
Constraints
- 2 โค nums.length โค 2 ร 104
- -231 โค nums[i] โค 231 - 1
- 0 โค indexDiff โค nums.length
- 0 โค valueDiff โค 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Deploy Cameras
Place cameras at different positions, each recording noise levels
2
Set Parameters
Define maximum distance between cameras and acceptable noise difference
3
Monitor Window
Use sliding window to only check cameras within distance limit
4
Bucket Classification
Group similar noise levels into buckets for efficient comparison
5
Detection
Alert when two cameras meet both distance and noise similarity criteria
Key Takeaway
๐ฏ Key Insight: By treating the problem as a smart city monitoring system, we see how bucket sort creates 'zones' of similar values, allowing instant detection of nearby cameras with similar readings, achieving optimal O(n) performance.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code