Problem Description
Given a 0-indexed integer array nums of length n, an integer indexDifference, and an integer valueDifference, find two indices i and j (where 0 ≤ i, j < n) that satisfy both:
- |i - j| ≥ indexDifference
- |nums[i] - nums[j]| ≥ valueDifference
If there exists such a pair, return any one pair [i, j]. Otherwise, return [-1, -1]. (Note: i and j are allowed to be equal.)
Key Insights
- The two conditions are independent and symmetric. Without loss of generality, you can look for a pair with i < j.
- When indexDifference > 0 (or when valueDifference > 0), i and j must be distinct; however, if both are 0 then even [0,0] is a valid answer.
- A brute force check over all pairs would be too slow for n up to 10⁵, so we need an O(n) or O(n log n) solution.
- For each index i, consider the range [i + offset, n - 1] (where offset is indexDifference if indexDifference > 0, and when indexDifference is 0 and valueDifference > 0, offset is taken as 1 because i by itself cannot provide a nonzero value difference).
- Precompute suffix arrays that store the minimum and maximum numbers (along with their indices) from a given position to the end. Then for each index i, one can check in O(1) time whether there exists a later index that satisfies the value difference condition.
Space and Time Complexity
Time Complexity: O(n) – we preprocess suffix arrays in one pass and then iterate through indices once. Space Complexity: O(n) – additional arrays are used to store suffix minimums and maximums and their corresponding indices.
Solution
We first handle the special case: if indexDifference == 0 and valueDifference == 0, then [0, 0] is immediately valid. Otherwise, we define an offset: if indexDifference > 0 then offset = indexDifference; if indexDifference == 0 but valueDifference > 0 then we set offset = 1 because we need two distinct indices to have a nonzero difference in value.
We build two suffix arrays:
- suffixMin: at each index i, it stores the minimum value in nums from index i to the end, along with the index where this minimum occurred.
- suffixMax: similarly, it stores the maximum value and the corresponding index.
For each index i from 0 to n - offset:
- We look into the range starting at index (i + offset) (which represents all indices j where j - i is enough).
- We check if the absolute difference between nums[i] and the minimum or maximum value in that suffix range is at least valueDifference.
- If so, we return the pair [i, j] (using j as the index where that min or max occurred).
If no valid pair is found after scanning, we return [-1, -1].
Code Solutions
Below are the solutions in Python, JavaScript, C++, and Java with detailed line-by-line comments.