Minimum Absolute Difference - Problem

Imagine you have an array of distinct integers and you need to find all pairs of numbers that have the smallest possible difference between them. This is like finding the closest neighbors in a line of numbers!

Given an array arr of distinct integers, your task is to:

  1. Find the minimum absolute difference between any two elements in the array
  2. Return all pairs of elements that have exactly this minimum difference
  3. Each pair [a, b] should satisfy: a < b and b - a equals the minimum absolute difference
  4. Return the pairs in ascending order

Example: For array [4, 2, 1, 3], the minimum difference is 1, and the pairs with difference 1 are: [[1,2], [2,3], [3,4]]

Input & Output

example_1.py โ€” Basic case with consecutive differences
$ Input: arr = [4,2,1,3]
โ€บ Output: [[1,2],[2,3],[3,4]]
๐Ÿ’ก Note: After sorting: [1,2,3,4]. Adjacent differences are all 1, which is minimum. So all adjacent pairs are returned.
example_2.py โ€” Multiple minimum differences
$ Input: arr = [1,3,6,10,15]
โ€บ Output: [[1,3]]
๐Ÿ’ก Note: After sorting: [1,3,6,10,15]. Differences are 2,3,4,5. Minimum is 2, only pair [1,3] has this difference.
example_3.py โ€” Minimum case with two elements
$ Input: arr = [40,20]
โ€บ Output: [[20,40]]
๐Ÿ’ก Note: Only two elements, so only one pair possible: [20,40] with difference 20.

Constraints

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

Visualization

Tap to expand
Minimum Absolute Difference SolutionStep 1: Original Array4213Step 2: Sorted Array1234111Step 3: Find Adjacent Differences2 - 1 = 13 - 2 = 14 - 3 = 1Minimum difference = 1Step 4: Result Pairs[1,2][2,3][3,4]
Understanding the Visualization
1
Sort the Array
Arrange elements in ascending order: [4,2,1,3] โ†’ [1,2,3,4]
2
Find Minimum Adjacent Difference
Compare only adjacent elements: 2-1=1, 3-2=1, 4-3=1. Minimum is 1.
3
Collect Pairs
All adjacent pairs with difference 1: [1,2], [2,3], [3,4]
Key Takeaway
๐ŸŽฏ Key Insight: After sorting the array, the minimum absolute difference will always be between adjacent elements, eliminating the need to check all pairs!
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 18
42.0K Views
Medium Frequency
~15 min Avg. Time
1.9K 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