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:
- Find the minimum absolute difference between any two elements in the array
- Return all pairs of elements that have exactly this minimum difference
- Each pair
[a, b]should satisfy:a < bandb - aequals the minimum absolute difference - 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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code