VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-a-pair-with-difference-between-values-and-indices-in-the-array/

⇱ Pair with Given Index and Value Diff Limits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Pair with Given Index and Value Diff Limits

Last Updated : 13 Jun, 2026

Given an integer array arr[], and integers idxDiff and valDiff, find whether there exists a pair of indices (i, j) such that:

  • i != j
  • abs(i - j) ≤ indDiff
  • abs(arr[i] - arr[j]) ≤ valDiff

Return true if such a pair exists; otherwise, return false.

Examples:

Input: arr[] = [1, 2, 3, 1], idxDiff = 3, valDiff = 0
Output: true
Explanation: The pair of indices (0, 3) satisfies all the conditions: abs(0 - 3) = 3 and abs(arr[0] - arr[3]) = abs(1 - 1) = 0.

Input: arr[] = [1, 5, 9, 1, 5, 9], idxDiff = 2, valDiff = 3
Output: false
Explanation: No pair of indices satisfies both the conditions.

[Naive Approach] Check All Valid Pairs - O(n * idxDiff) Time O(1) Space

The idea is to check all pairs of elements whose indices differ by at most idxDiff. For each such pair, check whether the absolute difference between their values is at most valDiff. If a valid pair is found, return true; otherwise, return false after examining all possible pairs.


Output
true

Time Complexity: O(n * idxDiff)
Auxiliary Space: O(1)

[Expected Approach] Sliding Window and Ordered Set - O(n log idxDiff) Time and O(idxDiff) Space

The idea is to maintain a sliding window of the last idxDiff elements using an ordered set. For each element, we search for a value in the current window that lies within the range [arr[i] - valDiff, arr[i] + valDiff]. If such a value exists, a valid pair is found. The sliding window is updated by inserting the current element and removing elements that fall outside the allowed index difference range.

Let us understand with example:
Input: arr[] = [1, 2, 3, 1], idxDiff = 3, valDiff = 0

  • Process 1: Set = {1}
  • Process 2: No element in range [2, 2], insert 2. Set = {1, 2}
  • Process 3: No element in range [3, 3], insert 3. Set = {1, 2, 3}
  • Process last 1: Element 1 is found in range [1, 1].
  • Valid pair found, so return true.

Output
true

Time Complexity: O(n log idxDiff)
Auxiliary Space: O(idxDiff)

Comment