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 x=2Input Array:4324i=0i=1i=2i=3Valid Pairs (|i-j| >= 2):i=0, j=2: |4-2| = 2i=0, j=3: |4-4| = 0 ✓i=1, j=3: |3-4| = 1Minimum Difference = 0
Understanding the Visualization
1
Input
Array [4,3,2,4] with constraint x=2
2
Valid Pairs
Find all pairs where |i-j| >= 2
3
Output
Minimum absolute difference = 0
Key Takeaway
🎯 Key Insight: Use a sorted data structure to efficiently find the closest value among valid candidates
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