Minimum Absolute Difference Between Elements With Constraint - Problem

You are given a 0-indexed integer array nums and an integer x.

Find the minimum absolute difference between two elements in the array that are at least x indices apart.

In other words, find two indices i and j such that abs(i - j) >= x and abs(nums[i] - nums[j]) is minimized.

Return an integer denoting the minimum absolute difference between two elements that are at least x indices apart.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,3,2,4], x = 2
Output: 0
💡 Note: We can choose indices i=0 and j=3 where abs(0-3) = 3 >= 2 and abs(nums[0] - nums[3]) = abs(4-4) = 0
Example 2 — No Exact Match
$ Input: nums = [5,3,2,10,15], x = 1
Output: 1
💡 Note: The minimum difference is 1 between elements 3 and 2 at indices 1 and 2 where abs(1-2) = 1 >= 1
Example 3 — Larger Gap Required
$ Input: nums = [1,2,3,4], x = 3
Output: 3
💡 Note: Only valid pair is indices 0 and 3: abs(0-3) = 3 >= 3 and abs(1-4) = 3

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ x ≤ nums.length - 1
  • 0 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Absolute Difference With Constraint INPUT Array nums: 4 i=0 3 i=1 2 i=2 4 i=3 x = 2 Indices must be at least 2 positions apart Valid Pairs: (i=0, j=2): |4-2| = 2 (i=0, j=3): |4-4| = 0 (i=1, j=3): |3-4| = 1 |j - i| >= 2 ALGORITHM STEPS 1 Initialize Sorted Set Empty set to store values 2 Sliding Window For i from x to n-1 3 Add to Set Insert nums[i-x] to set 4 Find Closest Binary search for nums[i] Execution Trace: i=2: set={4}, nums[2]=2 closest=4, diff=2 i=3: set={4,3}, nums[3]=4 closest=4, diff=0 min_diff = 0 [FOUND!] FINAL RESULT Optimal Pair Found: 4 i=0 3 2 4 j=3 |j-i| = 3 >= 2 Output: 0 Calculation: |nums[0] - nums[3]| = |4 - 4| = 0 OK - Minimum! Key Insight: Using a Sorted Set (TreeSet/BST) allows O(log n) insertion and nearest-neighbor queries. The sliding window ensures elements in the set are always at least x indices behind current position. Time Complexity: O(n log n) | Space Complexity: O(n) for the sorted set. TutorialsPoint - Minimum Absolute Difference Between Elements With Constraint | Sliding Window with Sorted Set
Asked in
Google 25 Amazon 20 Microsoft 15
21.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen