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 II INPUT nums array: 5 i=0 1 i=1 4 i=2 1 i=3 Parameters: indexDifference = 2 valueDifference = 4 Need to find i, j where: |i - j| >= 2 |nums[i] - nums[j]| >= 4 Both indices in [0, n-1] ALGORITHM STEPS 1 Initialize Tracking Track min/max values in window [0, j-indexDiff] 2 Slide Window For j from indexDiff to n-1 expand valid i range 3 Check Conditions |nums[j]-min| >= valueDiff |nums[j]-max| >= valueDiff 4 Return Result Found: return [i, j] Not found: [-1, -1] Trace: j=3 Valid i range: [0,1] min=1 (i=1), max=5 (i=0) |5-1|=4 >= 4 OK Return [0, 3] FINAL RESULT Valid pair found: 5 i=0 1 4 1 j=3 Verification: |0 - 3| = 3 >= 2 OK |5 - 1| = 4 >= 4 OK Output: [0, 3] Both conditions satisfied! Key Insight: Track running min/max values with their indices as window expands. For each j, the valid i range is [0, j-indexDiff]. Compare nums[j] against min and max to find valueDifference in O(1) per position. Time: O(n) | Space: O(1) - Linear scan with constant extra space! TutorialsPoint - Find Indices With Index and Value Difference II | Min/Max Tracking Approach
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