Minimum Absolute Difference

Easy

Topics
ArraySorting

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

Return the pairs in ascending order, each pair as [a, b] with a < b, and the list of pairs sorted by a.

Example 1

given4213
sorted1234
a closest pair
The closest two values are always neighbours once sorted, and the values are distinct so there are no ties at a single position. The smallest gap here is 1, and every pair achieving it belongs in the answer, not just the first.
Top row is the input; below it the same values sorted, with the closest pairs shaded.
Input:  arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The smallest difference is 1, achieved by three pairs.

Example 2

given1361015
sorted1361015
a closest pair
Input:  arr = [1,3,6,10,15]
Output: [[1,3]]
Explanation: The smallest difference is 2.

Example 3

given38-102319-4-1427
sorted-14-10-438192327
a closest pair
Input:  arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]
Explanation: The smallest difference is 4.

Constraints

  • 2 <= arr.length <= 10^5
  • -10^6 <= arr[i] <= 10^6
  • All values in arr are distinct.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The closest two values in a set are always neighbours once it is sorted. Anything between them would be closer to each, and the values are distinct so there are no ties to worry about at a single position.

So the search shrinks from every pair to just the n-1 adjacent pairs.

Approach

  1. Sort the array ascending.
  2. Scan the adjacent differences once to find the smallest.
  3. Scan again and collect every adjacent pair whose difference equals it.
  4. Because the input is sorted, the pairs come out ordered by their first element already, which is the output order required.

Walkthrough

arr = [4, 2, 1, 3]

sorted: [1, 2, 3, 4]
diffs:    1  1  1   -> minimum 1
collect: [1,2], [2,3], [3,4]

Complexity

  • Time — O(n log n): dominated by the sort; the two scans afterwards are linear.
  • Space — O(n): the output, plus whatever the sort uses.

Common Pitfalls

  • Comparing all pairs is quadratic and times out on the stated input size.
  • Every pair achieving the minimum is wanted, not just the first one found.

Full Solution — all languages

class Solution:
    def minimumAbsDifference(self, nums):
        nums = sorted(nums)
        best = min(nums[i + 1] - nums[i] for i in range(len(nums) - 1))
        return [[nums[i], nums[i + 1]] for i in range(len(nums) - 1)
                if nums[i + 1] - nums[i] == best]
SensAI
Beta
Tap the mic to stop voice mode