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

The returned values differ from original indices. Sorting a copy is appropriate here because values are requested, while sorting the caller's array would violate preservation.

Discarding pairs by their sum

Start at the smallest and largest sorted values. If their sum is too small, every pair using that left value and any smaller right value is also too small; advance left. If too large, every pair using that right value and any larger left value is too large; decrease right. Each step discards a provably impossible family of pairs.

The first matching left value is the smallest feasible one, giving the required lexicographic tie rule. Keep left strictly before right so a single element is never reused. One 5 cannot make 10 alone; two copies of 5 can.

JavaScript's default sort compares string representations, so it orders 10 before 2. Pass a numeric comparator and sort a copied array. Negative numbers do not invalidate the pointer argument, which depends on order rather than positivity.

JavaScript
const original = [10, 2, -1];
const sorted = [...original].sort((a, b) => a - b);
console.log(sorted); // [-1, 2, 10]
console.log(original); // [10, 2, -1]

Keeping values separate from positions

Sorting costs O(n log n), the inward scan costs O(n), and the copied array uses O(n) space. A hash-based existence query may be faster when any pair suffices, but the canonical smallest-value answer still needs a careful ordering policy. Use sorted pointers when order supports a clear elimination proof.

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