Find Indices With Index and Value Difference II - Problem
๐ฏ Find Indices With Index and Value Difference II
You're given a 0-indexed integer array nums of length n, along with two constraints: indexDifference and valueDifference.
Your mission: Find two indices i and j (both in range [0, n-1]) that satisfy both conditions:
- ๐ Index constraint:
abs(i - j) >= indexDifference - ๐ Value constraint:
abs(nums[i] - nums[j]) >= valueDifference
Return: An array [i, j] if such indices exist, otherwise [-1, -1]. If multiple valid pairs exist, return any one of them.
Note: Indices i and j can be equal if they satisfy both constraints.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [4,1,2,3], indexDifference = 1, valueDifference = 1
โบ
Output:
[0,2]
๐ก Note:
Indices 0 and 2 satisfy both constraints: |0-2| = 2 โฅ 1 and |4-2| = 2 โฅ 1. Other valid pairs exist like [0,1] but we return the first found.
example_2.py โ No Solution
$
Input:
nums = [1,2,3], indexDifference = 2, valueDifference = 4
โบ
Output:
[-1,-1]
๐ก Note:
No pair of indices satisfies both constraints. The maximum index difference is 2 (indices 0,2) but |1-3| = 2 < 4, so the value difference constraint fails.
example_3.py โ Same Index Valid
$
Input:
nums = [5], indexDifference = 0, valueDifference = 0
โบ
Output:
[0,0]
๐ก Note:
Single element array where i=j=0 satisfies both constraints: |0-0| = 0 โฅ 0 and |5-5| = 0 โฅ 0.
Visualization
Tap to expand
Understanding the Visualization
1
Setup Window
Start checking from positions that satisfy minimum distance
2
Track Extremes
Keep track of minimum and maximum activity levels from valid previous positions
3
Compare Current
Check if current position has sufficient activity difference with tracked extremes
4
Found Solution
Return the first valid pair that satisfies both distance and activity constraints
Key Takeaway
๐ฏ Key Insight: Instead of checking all pairs (O(nยฒ)), we use sliding window technique to track min/max values from valid previous positions, achieving optimal O(n) time complexity.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, each operation is O(1)
โ Linear Growth
Space Complexity
O(1)
Only using a few variables to track min/max values and indices
โ Linear Space
Constraints
- 1 โค nums.length โค 105
- 0 โค nums[i] โค 5 ร 104
- 0 โค indexDifference โค nums.length
- 0 โค valueDifference โค 5 ร 104
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code