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
04
19
211
314
4i − 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.
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