Minimum Absolute Difference Queries - Problem

The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1.

For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different.

You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive).

Return an array ans where ans[i] is the answer to the ith query.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,5,2,7,10], queries = [[0,2]]
Output: [1]
💡 Note: Query [0,2] gives subarray [4,5,2]. Checking differences: |4-5|=1, |4-2|=2, |5-2|=3. Minimum is 1.
Example 2 — Multiple Queries
$ Input: nums = [1,3,4], queries = [[0,1],[1,2]]
Output: [2,1]
💡 Note: Query [0,1] gives [1,3], difference |1-3|=2. Query [1,2] gives [3,4], difference |3-4|=1.
Example 3 — All Same Elements
$ Input: nums = [5,5,5], queries = [[0,2]]
Output: [-1]
💡 Note: All elements in subarray [5,5,5] are identical, so no valid pairs with different values exist.

Constraints

  • 2 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 100
  • 1 ≤ queries.length ≤ 2 × 104
  • 0 ≤ li < ri < nums.length

Visualization

Tap to expand
Minimum Absolute Difference Queries INPUT nums array: 4 [0] 5 [1] 2 [2] 7 [3] 10 [4] Query: [0, 2] Subarray: nums[0..2] 4 5 2 Input Values: nums = [4,5,2,7,10] queries = [[0,2]] Range: index 0 to 2 ALGORITHM STEPS 1 Extract Subarray Get nums[0..2] = [4,5,2] 2 Sort Subarray Sorted: [2, 4, 5] 2 4 5 3 Compare Adjacent Find min diff in sorted |4-2| = 2 |5-4| = 1 4 Return Minimum min(2, 1) = 1 Optimal Approach: Use prefix counts for values Values limited to 1-100 range O(100 * queries) time FINAL RESULT For Query [0, 2]: Subarray: [4, 5, 2] Sorted: [2, 4, 5] Differences: 2, 1 Min Diff = 1 Output Array: [1] OK - Answer Found ans[0] = 1 |5 - 4| = 1 is minimum Key Insight: In a sorted array, the minimum absolute difference is always between adjacent elements. Since values are bounded (1-100), use prefix sums to count occurrences in any range efficiently, then iterate through present values to find minimum gap between consecutive distinct values. TutorialsPoint - Minimum Absolute Difference Queries | Optimal Solution
Asked in
Amazon 15 Google 12
12.5K Views
Medium Frequency
~25 min Avg. Time
485 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