679. Every Pair at the Smallest Distance
Find the smallest difference between any two values, then print every pair of VALUES achieving it.
Print how many such pairs there are, then the pairs themselves, each as the smaller value followed by the larger, in increasing order. A pair of values is reported once however many positions realise it.
4 2 1 3 -> 3
1 2
2 3
3 4
1 3 6 10 15 -> 1
1 3
2 2 4 4 -> 2
2 2
4 4
## The closest pair is always adjacent after sorting
Sort. If two values are separated by anything, the values between them are closer to each of them than they are to each other, so no non-adjacent pair can beat every adjacent one.
That is the whole reduction: the C(n, 2) pairs collapse to the n - 1 adjacent ones.
## Two passes over the adjacent gaps
first pass: smallest = min over i of a[i] - a[i-1]
second pass: report every i with a[i] - a[i-1] == smallest
Both passes are a cursor and its predecessor walking together, which is the simplest possible two-pointer shape.
Doing it in one pass, by resetting the list whenever a smaller gap appears, also works and needs care: the list must be cleared, not appended to. Two passes avoid that entirely and cost one extra scan.
## Duplicates and the zero gap
Equal values give a gap of 0, which is the smallest possible, so whenever any value repeats the answer consists only of repeated-value pairs.
2 2 4 4 answers 2 2 and 4 4, not 2 4. And a pair of VALUES is reported once, so
1 1 1 gives just 1 1 even though three position pairs realise it. The second pass must
therefore skip a gap that repeats the pair it has just reported.
## Boundaries
Two values give exactly one pair. Every value distinct and evenly spaced gives n - 1 pairs,
all at the same gap.
## Cost
Time O(n log n) for the sort. Space O(1) beyond the output.
Constraints - `2 ≤ n ≤ 200000` - `-10^9 ≤ each value ≤ 10^9`
Input
The first line contains an integer n.
The second line contains n integers.
Output
Print the number of pairs on the first line, then each pair on its own line as two integers separated by a space, in increasing order.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.