KatInterview

Collect All Closest Adjacent Value Pairs

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortinggreedyarrays

Last updated

Tests sorting and greedy scanning to identify the smallest gap between elements and extract all pairs achieving it.

You are given an integer array nums which may be unsorted and may contain duplicate values.

Your task is to identify the smallest absolute difference between any two elements at distinct positions in the array, then return all pairs of values that achieve this smallest difference.

Each pair must be formatted as [smaller_value, larger_value] (the smaller value comes first). The list of pairs should be sorted in ascending order: first by the smaller value, then by the larger value if needed.

Constraints

  • 0 ≤ len(nums) ≤ 10⁵
  • -10⁶ ≤ nums[i] ≤ 10⁶
  • If fewer than two elements exist, return an empty list
  • Elements are compared by position, not by value (so duplicate values at different positions form valid pairs)

Examples

Example 1

Input: closest_value_pairs([-1, -2, -4, -5, 7, 10])

Output: [[-5, -4], [-2, -1]]

Hints

Hint 1

After sorting the array, which pairs of elements are guaranteed to have the smallest possible differences?

Hint 2

The minimum difference can only occur between adjacent elements in the sorted array—non-adjacent pairs will always have a larger or equal gap.

Hint 3

Once you find the minimum gap, a second pass through adjacent pairs collects all matches.