JJobsMoi
PayPal

Minimum Absolute Difference

Codingeasy

Problem

You are given an integer array nums of distinct integers. Consider every possible pair of numbers from the array, and for each pair compute the absolute value of their difference. Let m be the smallest such absolute difference across all pairs in the array.

Your task is to return every pair of elements from nums whose absolute difference equals m. Each pair should be reported as a two-element list [a, b] where a < b.

Rules to follow:

  • Return the result as a list of pairs, ordered by increasing value of a (the smaller element in each pair).
  • Every pair [a, b] in your answer must actually satisfy b - a == m, the overall minimum difference — not just be some small difference.
  • All values in nums are guaranteed distinct, so you never need to worry about a pair with difference zero.

Examples

Example 1:

Input: nums = [7, 2, 10, 4]

Output: [[2, 4], [4, 7]]

Explanation:

  • Sorting gives [2, 4, 7, 10]. The consecutive gaps are 4-2=2, 7-4=3, 10-7=3.
  • The smallest gap is 2, achieved by the pairs (2, 4) and (4, 7), so both are returned in increasing order of their smaller element.

Example 2:

Input: nums = [1, 5, 9]

Output: [[1, 5], [5, 9]]

Explanation:

  • Sorted, the array is already [1, 5, 9], with consecutive gaps 4 and 4.
  • Both gaps tie for the minimum value of 4, so both pairs are included in the answer.

Constraints

  • 2 <= nums.length <= 10^5
  • -10^6 <= nums[i] <= 10^6
  • All elements of nums are distinct.

Solution

Loading editor…

Sign in to get AI feedback on your answer. Your work is saved while you do.

Sign in to evaluate