DSA Factory
Free lessonsSorting · Stage 0 · Sort it first · Step 2

Neighbours after sorting

Once sorted, the closest values sit side by side. About 8 minutes.

Sorting brings close values together

In 9, 1, 14, 4, 11 the two closest values are 9 and 11, but they are far apart in the list. Sort it and you get 1, 4, 9, 11, 14, and now they stand side by side, like two friends who finally get seated together.

In a sorted list the closest pair is always a pair of neighbours.

Why neighbours? If a value sits between two others, it is closer to each of them than they are to each other, so those two were never the closest.
Closest pair in [9, 1, 14, 4, 11], sorted to [1, 4, 9, 11, 14]
1
0
4
1
9
2
11
3
14
4
i − 1i

4 − 1 = 3. Best so far: 3.

Move 1 of 5

Then one walk over the neighbours

Walk along the sorted list and, at each step, measure the gap between a value and the one just before it. Keep the smallest gap you have seen. That is n − 1 checks instead of comparing every pair.

The same trick finds repeats: equal values end up next to each other, with a gap of 0.

Start at the second value: and compare it with the one before.
A repeat: gives a gap of 0, the smallest possible.
In code
nums.sort()
best = nums[1] - nums[0]
for i in range(2, len(nums)):
    gap = nums[i] - nums[i - 1]
    best = min(best, gap)
return best
Quick check

nums is sorted: [2, 5, 6, 10]. Which pairs do you need to check to find the closest two?

  1. AOnly 2 and 5, 5 and 6, 6 and 10
  2. BAll six pairs
  3. COnly 2 and 10
Show the answer

Only 2 and 5, 5 and 6, 6 and 10. In a sorted list the closest pair is always two neighbours, so three checks are enough.

Your problem

The closest pair

Return the smallest difference between two values in nums (the bigger one minus the smaller one). The two values must be at different positions. nums has at least two values.

Example
nums = [9, 1, 14, 4, 11] → 2

2 ≤ n ≤ 500,000 · 0 ≤ each value ≤ 1,000,000,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding