Find Indices With Index and Value Difference I - 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, and
  • 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 = [4,1,2,3], indexDifference = 1, valueDifference = 1
Output: [2,3]
💡 Note: At indices 2 and 3: abs(2-3) = 1 >= 1 (index diff), abs(2-3) = 1 >= 1 (value diff). Both conditions satisfied.
Example 2 — No Valid Pair
$ Input: nums = [1,2,3], indexDifference = 2, valueDifference = 4
Output: [-1,-1]
💡 Note: Only valid index pairs are (0,2) with values (1,3). Value difference is |1-3| = 2 < 4, so no solution exists.
Example 3 — Same Index
$ Input: nums = [5], indexDifference = 0, valueDifference = 0
Output: [0,0]
💡 Note: With single element and both differences = 0, we can return the same index twice: abs(0-0) = 0 >= 0, abs(5-5) = 0 >= 0.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ indexDifference ≤ nums.length - 1
  • 0 ≤ valueDifference ≤ 50
  • 0 ≤ nums[i] ≤ 50

Visualization

Tap to expand
Find Indices With Index and Value Difference I INPUT nums array: 0 1 2 3 4 1 2 3 Parameters: indexDifference = 1 valueDifference = 1 Conditions to satisfy: |i - j| >= 1 |nums[i] - nums[j]| >= 1 Find valid pair [i, j] ALGORITHM STEPS 1 Initialize Two Pointers Track min/max in prefix 2 Iterate with j pointer j from indexDiff to n-1 3 Update min/max indices At position i = j - indexDiff 4 Check value difference Compare nums[j] with extremes Iteration Trace: j=1: i=0, nums[0]=4 j=2: i=1, min=1, max=4 j=3: |nums[2]-nums[3]|=1 --> Found! [2,3] FINAL RESULT Valid pair found: 0 1 2=i 3=j 4 1 2 3 Output: [2, 3] Verification: Index check: |2 - 3| = 1 >= 1 OK Value check: |2 - 3| = 1 >= 1 OK Key Insight: The optimized two-pointer approach maintains running min/max values in the prefix that satisfies the index difference constraint. This allows O(n) time complexity instead of O(n^2) brute force. TutorialsPoint - Find Indices With Index and Value Difference I | Optimized Two Pointers O(n) Time
Asked in
Google 15 Microsoft 12
8.5K Views
Medium Frequency
~15 min Avg. Time
234 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