Minimum Absolute Difference - Problem

Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.

Return a list of pairs in ascending order (with respect to pairs), each pair [a, b] follows:

  • a, b are from arr
  • a < b
  • b - a equals to the minimum absolute difference of any two elements in arr

Input & Output

Example 1 — Basic Case
$ Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
💡 Note: After sorting: [1,2,3,4]. Adjacent differences: |2-1|=1, |3-2|=1, |4-3|=1. Minimum difference is 1, so all adjacent pairs qualify.
Example 2 — Single Pair
$ Input: arr = [1,3,6,10,15]
Output: [[1,3]]
💡 Note: After sorting: [1,3,6,10,15]. Adjacent differences: |3-1|=2, |6-3|=3, |10-6|=4, |15-10|=5. Minimum difference is 2, only pair [1,3] qualifies.
Example 3 — Multiple Minimum Pairs
$ Input: arr = [1,1,3,3]
Output: [[1,3],[1,3]]
💡 Note: After sorting: [1,1,3,3]. Adjacent differences: |1-1|=0, |3-1|=2, |3-3|=0. Wait, this violates distinct constraint. Let's use [1,5,3,4]: sorted [1,3,4,5], differences [2,1,1], min=1, pairs [[3,4],[4,5]].

Constraints

  • 2 ≤ arr.length ≤ 105
  • -106 ≤ arr[i] ≤ 106
  • All integers in arr are distinct

Visualization

Tap to expand
Minimum Absolute Difference INPUT Original Array: arr 4 2 1 3 [0] [1] [2] [3] Input Details arr = [4, 2, 1, 3] Length: 4 elements Goal: Find all pairs with minimum absolute difference Distinct integers only ALGORITHM STEPS 1 Sort the Array [4,2,1,3] --> [1,2,3,4] 1 2 3 4 2 Find Min Difference Compare adjacent pairs: 2-1=1, 3-2=1, 4-3=1 Min diff = 1 3 Collect Valid Pairs Find pairs with diff = 1 [1,2] diff=1 OK [2,3] diff=1 OK [3,4] diff=1 OK 4 Return Result Already sorted (a < b) Time: O(n log n) FINAL RESULT Valid Pairs Found: 1 , 2 diff=1 2 , 3 diff=1 3 , 4 diff=1 OUTPUT: [[1,2],[2,3],[3,4]] OK - 3 pairs Key Insight: Sorting is the key! After sorting, minimum absolute difference can only occur between adjacent elements. This reduces the problem from O(n^2) comparisons to O(n) with one pass. TutorialsPoint - Minimum Absolute Difference | Optimal Solution
Asked in
Amazon 15 Google 12 Facebook 8 Microsoft 6
23.5K Views
Medium Frequency
~15 min Avg. Time
894 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