Data Structures & AlgorithmsVery hard

When counting pairs with a given sum in a sorted array using two pointers, why is sorting essential?

  1. A. Sorting makes the sum monotone in each pointer, so a too-small sum means moving the left pointer right and a too-large sum means moving the right pointer left.
  2. B. Sorting removes duplicate values so each pair is counted once.
  3. C. Sorting makes the array smaller in memory.
  4. D. Sorting guarantees the answer equals the number of elements.

Correct answer: A. Sorting makes the sum monotone in each pointer, so a too-small sum means moving the left pointer right and a too-large sum means moving the right pointer left.

In a sorted array the sum of a pair is monotone as either index moves, which lets one pointer decide each step. The method is O(n) after the O(n log n) sort.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic