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) >= 2, and
abs(nums[i] - nums[j]) >= 4
Return an integer arrayanswer, whereanswer = [i, j]if there are two such indices , andanswer = [-1, -1]otherwise. If there are multiple choices for the two indices, return any of them.
Input: nums =[5,1,4,1], indexDifference =2, valueDifference =4Output: [0,3]Explanation: In this example, i =0 and j =3 can be selected.abs(0-3)>=2 and abs(nums[0]- nums[3])>=4.Hence, a valid answer is[0,3].[3,0]is also a valid answer.
Input: nums =[2,1], indexDifference =0, valueDifference =0Output: [0,0]Explanation: In this example, i =0 and j =0 can be selected.abs(0-0)>=0 and abs(nums[0]- nums[0])>=0.Hence, a valid answer is[0,0].Other valid answers are [0,1],[1,0], and [1,1].
Input: nums =[1,2,3], indexDifference =2, valueDifference =4Output: [-1,-1]Explanation: In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.Hence,[-1,-1]is returned.
Since the constraints are large, a brute-force approach is too slow. We can use a sliding window and monotonic queues to efficiently track the minimum and maximum values in a window of size at least indexDifference.
Use two monotonic deques: one for the minimum and one for the maximum in the window.
For each index i, maintain the window of indices at least indexDifference apart.
For each i, check if there exists a j (with |i-j| >= indexDifference) such that |nums[i] - nums[j]| >= valueDifference by comparing with the min and max in the window.
classSolution:
deffindIndices(self, nums: list[int], indexDifference: int, valueDifference: int) -> list[int]:
from collections import deque
n = len(nums)
minq, maxq = deque(), deque()
for i in range(n):
if i >= indexDifference:
while minq and minq[0] < i - indexDifference:
minq.popleft()
while maxq and maxq[0] < i - indexDifference:
maxq.popleft()
if abs(nums[i] - nums[minq[0]]) >= valueDifference:
return [i, minq[0]]
if abs(nums[i] - nums[maxq[0]]) >= valueDifference:
return [i, maxq[0]]
while minq and nums[i] <= nums[minq[-1]]:
minq.pop()
minq.append(i)
while maxq and nums[i] >= nums[maxq[-1]]:
maxq.pop()
maxq.append(i)
return [-1, -1]