Consider the leftmost person who has not yet been paired. Every earlier position already belongs to a pair, so the partner of must be to the right. Its position is therefore forced to be .
Reject if , if is already paired, or if . Otherwise mark both positions as paired and continue.
To prove correctness, maintain that every pair chosen so far belongs to every possible valid pairing. This holds initially. At the next unpaired position , no earlier position is available, so every valid extension must contain . If one of the checks fails, no such extension exists. If all checks pass, adding that pair preserves the invariant.
When the scan finishes, every person belongs to exactly one chosen pair and both endpoints of every pair report its actual distance. Thus the constructed pairing is valid. The same argument also shows that a valid pairing is unique.
The algorithm takes time and memory per test case. Across all cases its time is . Checking only how often each distance occurs is insufficient: positions matter.