Home/Data structures & algorithms/Sorting and two pointers

Sorting and two pointers

Discard impossible pairs using sorted order

An audit tool is checking whether two ledger adjustments explain a disputed total. Entries may be negative, and two equal amounts are allowed only if they come from different entries. When several pairs work, the report needs a reproducible choice.

Checking every pair is a useful reference. Sorting a copy gives the search a stronger property: a sum that is too small or too large can rule out a whole group of pairs at once.

Explaining a total with two entries

Sorted order lets one comparison discard a group of impossible pairs. A sum below target needs a larger left value; a sum above target needs a smaller right value. Distinct positions matter when both values are equal.

Discarding pairs by their sum

For sorted values [-2, 1, 4, 7, 10] and target 9, the outer pair sums to 8. No smaller partner can rescue -2, so move the left pointer. Now 1 + 10 is too large, and no larger left value can rescue 10, so move the right pointer. Each move has a reason; neither requires trying all partners for the discarded endpoint.

go
original := []int{4, 1, 3}
copyForSort := append([]int(nil), original...)
sort.Ints(copyForSort)

Keeping values separate from positions

A slice assignment would share the backing array and sorting it would mutate the caller. A value pair is different from an index pair; the tie rule here compares values. Sorting adds O(n log n) work but permits O(n) pointer scanning. Hash lookup can also find sums but requires additional care for this canonical pair rule.

The sorted-copy method takes O(n log n) sorting time, an O(n) inward scan, and O(n) copy space. The all-pairs reference has O(n²) candidates. For already sorted input, only the linear scan is needed; for original positions, retain their association with each value.

Sorting a copy leaves the original transaction order available for the rest of the audit.

Practice Sorting and two pointers

Implement the exercise in a full-screen workspace, then run its tests.

Open practice
Next lessonBinary search on the answer