![]() |
VOOZH | about |
Given an integer array arr[], and integers idxDiff and valDiff, find whether there exists a pair of indices (i, j) such that:
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.
Table of Content
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 mostvalDiff. If a valid pair is found, returntrue; otherwise, returnfalseafter examining all possible pairs.
true
Time Complexity: O(n * idxDiff)
Auxiliary Space: O(1)
The idea is to maintain a sliding window of the last
idxDiffelements 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
true
Time Complexity: O(n log idxDiff)
Auxiliary Space: O(idxDiff)