Data Structures & AlgorithmsVery hard

For the 'largest number from concatenation' problem, why does the comparator compare x+y with y+x as strings?

  1. A. It sorts the numbers by their numeric value.
  2. B. It removes leading zeros.
  3. C. It makes all numbers the same length.
  4. D. It decides which of two numbers should come first in the final string, since the string order is what the answer depends on.

Correct answer: D. It decides which of two numbers should come first in the final string, since the string order is what the answer depends on.

Two numbers placed adjacent produce either xy or yx; putting x first is better exactly when x+y > y+x as strings. A comparator with this rule yields the optimal total order.

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

Exams that ask this topic