Data Structures & AlgorithmsVery hard

When merging two sorted lists with the standard two-pointer method, how many comparisons are made in the worst case?

  1. A. At most n + m − 1 comparisons, since each comparison outputs one element and the last element needs no comparison.
  2. B. Exactly n·m comparisons.
  3. C. Exactly log(n + m) comparisons.
  4. D. Exactly n comparisons regardless of m.

Correct answer: A. At most n + m − 1 comparisons, since each comparison outputs one element and the last element needs no comparison.

Each comparison emits one element, and once one list is exhausted the rest is copied without comparisons. The worst case therefore uses at most n + m − 1 comparisons.

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

Exams that ask this topic