DSAVisualiseData Structures & Algorithms Studio
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 JSON

Edit the lesson input, then build a deterministic source-linked trace.

This lesson validates its own input and operation limits.

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.

Live snapshot

Current operation

Trace state
Ready 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

Java
ClosestPair.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