Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

After sorting distinct values, a minimum-gap pair must be adjacent. A nonadjacent pair spans at least one intervening gap and therefore cannot be closer than every adjacent pair inside it. Sorting also places the output pairs in the required order.

Approach

Sort the array and scan neighboring values. When their difference improves the minimum, replace the result list with that pair. When it ties the minimum, append the pair. Ignore larger differences. Return the collected pairs after the scan; replacing the list on an improvement removes pairs that are no longer globally minimal.

class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: n = len(arr) arr.sort() res = [] mn = inf for i in range(1, n): dif = arr[i] - arr[i - 1] if dif < mn: res = [[arr[i - 1], arr[i]]] mn = dif elif dif == mn: res.append([arr[i - 1], arr[i]]) return res

Complexity analysis

For n values, sorting costs O(n log n) and the adjacent-pair scan costs O(n), so time is O(n log n). The returned pairs use O(n) space in the worst case; sort workspace is language-dependent and can also be O(n).