FastPrepAll Minimum-Difference Pairs

All Minimum-Difference Pairs

Microsoft logoMicrosoft● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given an array of integers nums, find the minimum absolute difference between any two distinct input elements. Return every pair of values that attains that minimum.

For this exercise, all input values are distinct. Each output pair must be written as [smaller, larger], and the pairs must be sorted by their first value in ascending order. Return an empty array when there are fewer than two values.

Include every minimizing pair, even when several disjoint pairs or several adjacent pairs share the same minimum difference.

Function

minimumDifferencePairs(nums: int[]) → int[][]

Examples

Example 1

nums = [-1,-2,-4,-5,7,10]return = [[-5,-4],[-2,-1]]

The minimum absolute difference is 1. Both [-5,-4] and [-2,-1] attain it, in ascending output order.

Example 2

nums = [3,1,7,5]return = [[1,3],[3,5],[5,7]]

After ordering the values, every neighboring gap is 2, so all three pairs must be returned.

Example 3

nums = []return = []

Fewer than two values form no pair, so the result is empty.

Constraints

  • 0 <= nums.length <= 2000.
  • All values in nums are distinct.
  • -10^9 <= nums[i] <= 10^9.
  • Return each value pair once, in the stated order.

More Microsoft problems

See Microsoft hiring insights
public int[][] minimumDifferencePairs(int[] nums) {
    // Return all minimizing value pairs.
}
nums[-1,-2,-4,-5,7,10]
expected[[-5,-4],[-2,-1]]
Checking account…