Problem Description
Given an integer array and two integers indexDiff and valueDiff, determine whether there exist two distinct indices i and j such that the absolute difference of their indices is no more than indexDiff and the absolute difference of their values is no more than valueDiff.
Key Insights
- Use a sliding window of size indexDiff to ensure the index condition.
- To efficiently check the value condition, maintain a data structure with near-ordering.
- Bucket sort (or using an ordered set / BST) can help check for any element within [num - valueDiff, num + valueDiff] in O(1) average time.
- Use a bucket size of (valueDiff + 1) to map numbers to buckets. Two numbers in the same or adjacent buckets may satisfy the condition.
Space and Time Complexity
Time Complexity: O(n) on average (each element is processed once and bucket operations take constant time on average). Space Complexity: O(min(n, indexDiff)) since we only store the current sliding window’s elements.
Solution
The solution leverages bucket sort along with a sliding window. We use a hash map to maintain buckets, where each bucket size is defined as (valueDiff + 1). For each element:
- Compute its bucket ID.
- Check if this bucket already has a number (this guarantees the value difference is within valueDiff).
- Check the adjacent buckets (bucket-1 and bucket+1) for potential candidates.
- Insert the current number into its bucket.
- Once the sliding window exceeds the size indexDiff, remove the element that falls outside the window. This approach ensures both conditions (index and value constraints) are met efficiently.
Code Solutions
Below are implementations in Python, JavaScript, C++, and Java.