Sorting & Selection Easy
Closest Pair Sum
ClosestPair sorts an integer array and uses two pointers to find the pair whose sum is closest to a target.
Trace input
Bounded JSONEdit the lesson input, then build a deterministic source-linked trace.
Source scenarios
Complexity
BestO(n log n)
AverageO(n log n)
WorstO(n log n)
SpaceO(log n) for Java's primitive-array sort
Array state
Follow the active comparisons and writes.
Current operation
Trace stateReady to explore
Source behavior & common mistakes
Follow the low and high pointers through the sorted values. The source permits using one array entry twice, updates the saved pair only for a strictly smaller distance, and returns the mutated sorted array state.
- The goal is to make the pair's sum close to the target, not to find two individual values close to it.
- The source sorts the caller's array in place before the two-pointer scan.
- The same entry may be used twice; a one-element array therefore returns that value twice.
- Equal-distance candidates do not replace the first saved pair because the source uses strict <.
- Pair sums and target differences use Java int overflow; Math.abs(Integer.MIN_VALUE) remains negative.
Algorithm code
JavaClosestPair.java (pinned repository source)Step linked
The highlighted line follows the current step.
Ready to begin
Press Play to see what happens.
Detailed execution
Snapshot 1 / 1
Comparisons 0 · Pointer moves 0