Data Structures & AlgorithmsHardICPC regional · Product Company SDE

Problem: Two Sum on an unsorted array can be solved in O(n) using a hash map, or in O(n log n) using sort-and-two-pointers. Why might the O(n log n) approach still be chosen in practice?

  1. A. Because sorting is required by the problem statement
  2. B. When the original indices of the pair aren't needed (or can be tracked alongside), and extra hash-map memory overhead is undesirable, sorting avoids that O(n) auxiliary hashing cost
  3. C. Because hash maps cannot be used with integers
  4. D. Because O(n log n) is always faster than O(n)

Correct answer: B. When the original indices of the pair aren't needed (or can be tracked alongside), and extra hash-map memory overhead is undesirable, sorting avoids that O(n) auxiliary hashing cost

A hash-map pass is asymptotically faster, but it uses O(n) extra memory and hashing overhead; if indices aren't required (or are tracked through the sort), the two-pointer approach after sorting avoids that overhead at the cost of the sort itself.

More Coding Interview Problems questions

Exams that ask this topic