Find Indices With Index and Value Difference II - Problem

You are given a 0-indexed integer array nums having length n, an integer indexDifference, and an integer valueDifference.

Your task is to find two indices i and j, both in the range [0, n - 1], that satisfy the following conditions:

  • abs(i - j) >= indexDifference
  • abs(nums[i] - nums[j]) >= valueDifference

Return an integer array answer, where answer = [i, j] if there are two such indices, and answer = [-1, -1] otherwise.

If there are multiple choices for the two indices, return any of them.

Note: i and j may be equal.

Input & Output

Example 1 — Basic Case
$ Input: nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
Output: [0,3]
💡 Note: Index difference: |0-3| = 3 ≥ 2 ✓, Value difference: |5-1| = 4 ≥ 4 ✓
Example 2 — No Valid Pair
$ Input: nums = [2,1], indexDifference = 0, valueDifference = 0
Output: [0,0]
💡 Note: Index difference: |0-0| = 0 ≥ 0 ✓, Value difference: |2-2| = 0 ≥ 0 ✓
Example 3 — Large Differences Required
$ Input: nums = [1,2,3], indexDifference = 2, valueDifference = 4
Output: [-1,-1]
💡 Note: No pair satisfies both constraints: max value difference is |1-3| = 2 < 4

Constraints

  • 2 ≤ nums.length ≤ 5 × 105
  • 0 ≤ indexDifference < nums.length
  • 0 ≤ valueDifference ≤ 109
  • 0 ≤ nums[i] ≤ 5 × 108

Visualization

Tap to expand
Find Indices With Index and Value Difference II51410123indexDifference = 2valueDifference = 4Index Distance: |0-3| = 3 ≥ 2 ✓Value Distance: |5-1| = 4 ≥ 4 ✓Both conditions satisfied!Output: [0, 3]
Understanding the Visualization
1
Input
Array [5,1,4,1] with indexDiff=2, valueDiff=4
2
Process
Find indices i,j where |i-j|≥2 and |nums[i]-nums[j]|≥4
3
Output
Return [0,3] as |0-3|=3≥2 and |5-1|=4≥4
Key Takeaway
🎯 Key Insight: Use efficient min/max tracking to avoid checking all pairs while maintaining index difference constraints
Asked in
Google 12 Amazon 8 Microsoft 6
12.4K Views
Medium Frequency
~25 min Avg. Time
289 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