#2905

Find Indices With Index and Value Difference II

Medium
ArrayTwo PointersSliding WindowDeque
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can optimize the search by using a sliding window approach. This allows us to maintain a range of indices and check the minimum and maximum values efficiently.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a deque to keep track of indices for the sliding window.
  2. 2Step 2: Iterate through each index i from 0 to n-1.
  3. 3Step 3: Remove indices from the deque that are out of the valid range (i - indexDifference).
  4. 4Step 4: Check the minimum and maximum values in the deque against nums[i] to see if they satisfy the valueDifference condition.
  5. 5Step 5: If a valid pair is found, return the indices. If no valid pairs are found by the end, return [-1, -1].
solution.py15 lines
1from collections import deque
2
3def find_indices(nums, indexDifference, valueDifference):
4    n = len(nums)
5    window = deque()
6    for i in range(n):
7        while window and window[0] < i - indexDifference:
8            window.popleft()
9        if window:
10            if abs(nums[i] - nums[window[0]]) >= valueDifference:
11                return [i, window[0]]
12            if abs(nums[i] - nums[window[-1]]) >= valueDifference:
13                return [i, window[-1]]
14        window.append(i)
15    return [-1, -1]

Complexity note: This complexity is achieved because we only traverse the array once, and the deque operations (adding/removing) are efficient.

  • 1Using a sliding window can significantly reduce the number of comparisons needed.
  • 2Maintaining a deque allows us to efficiently track the minimum and maximum values within a range.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.