Data Structures & AlgorithmsVery hard
When counting pairs with a given sum in a sorted array using two pointers, why is sorting essential?
- 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.
- B. Sorting removes duplicate values so each pair is counted once.
- C. Sorting makes the array smaller in memory.
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- The 3-sum two-pointer method skips a value when it equals the previous value. Why?
- What is the lexicographically smallest array of length n with positive integers and total sum S (S ≥ n)?
- In the 'minimum swaps to sort a permutation' problem, why is the answer n minus the number of cycles?
- Which statement about a monotonic deque for sliding-window minimum is correct?
- Why is prefix-sum counting of zero-sum subarrays unaffected by the choice of starting index for the prefix array?
- For the sum-at-most-K problem on a prefix-sum array with negative values, why does a balanced search structure appear in the solution?