Problem 313784 · easy · Phase 03 Linear Management & Searching

Closest Pair by Value

sorting · sort-then-scan · adjacent comparison

Given a list of integers nums with at least two elements, find two elements whose absolute difference is as small as possible and return them as a list [a, b] with a <= b.

If several pairs share the smallest difference, return the one with the smallest a.

Examples

Input:  nums = [4, 9, 1, 7, 3]
Output: [3, 4]
Explanation: 4 - 3 = 1 is the smallest difference between any two elements.
Input:  nums = [1, 3, 5]
Output: [1, 3]
Explanation: Both (1, 3) and (3, 5) differ by 2; the pair with the smaller first value wins.

Constraints

  • 2 <= len(nums) <= 10**5
  • -10**9 <= nums[i] <= 10**9; duplicates are allowed (a difference of 0 is possible).
  • Target complexity: O(n log n).

Goals

  • Recognise that the closest pair of values is adjacent after sorting
  • Scan adjacent pairs once and keep the best
  • Apply a tie-breaking rule while scanning
Starting Python…