1200. Minimum Absolute Difference
EasyView on LeetCode
Time: O(n log n)
Space: O(n)
Problem Overview
After sorting, the minimum absolute difference between any two elements always occurs between neighbors.
Intuition
After sorting, the minimum absolute difference between any two elements always occurs between neighbors. Scan adjacent pairs for the minimum diff, then collect every pair achieving that diff.
Algorithm
- 1Sort nums ascending.
- 2One pass: track minDiff = min(nums[i+1]-nums[i]).
- 3Second pass: add [nums[i], nums[i+1]] whenever nums[i+1]-nums[i] == minDiff.
- 4Return list of pairs (order as in sorted array).
Example Walkthrough
Input: nums = [4,2,1,3]
- 1.Sorted: [1,2,3,4]. Adjacent diffs: 1,1,1.
- 2.All adjacent pairs have diff 1.
Output: [[1,2],[2,3],[3,4]]
Common Pitfalls
- •Sort first — unsorted scan misses global minimum diff.
- •Only compare adjacent elements after sort.
- •Include all pairs tied for minimum difference.
1200.cs
C#
// Approach: Sort the array; scan adjacent pairs to find the minimum difference, then collect all pairs with that difference.
// Time: O(n log n) Space: O(n)
public class Solution
{
public IList<IList<int>> MinimumAbsDifference(int[] arr)
{
IList<IList<int>> result = new List<IList<int>>();
Array.Sort(arr);
long minDifference = Int64.MaxValue;
for (int i = 0; i < arr.Length - 1; i++)
{
var difference = Math.Abs(arr[i] - arr[i + 1]);
if (difference < minDifference)
minDifference = difference;
}
for (int j = 0; j < arr.Length - 1; j++)
{
var difference = Math.Abs(arr[j] - arr[j + 1]);
if (minDifference == difference)
{
var minDifflist = new List<int> { arr[j], arr[j + 1] };
result.Add(minDifflist);
}
}
return result;
}
}Was this solution helpful?
Related Problems
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 56. Merge Intervals(Medium)
- 75. Sort Colors(Medium)
- 179. Largest Number(Medium)
- 218. The Skyline Problem(Hard)