Data Structures & AlgorithmsVery hardProduct Company SDE · sorting with comparator

Problem: Arrange the numbers 3, 30, 34, 5, 9 so that the concatenation is the largest possible. Run the code and state the printed string.

Problem: Arrange the numbers 3, 30, 34, 5, 9 so that the concatenation is the largest possible. Run the code and state the printed string.
from functools import cmp_to_key
a = ['3', '30', '34', '5', '9']
a.sort(key=cmp_to_key(lambda x, y: -1 if x + y > y + x else (1 if x + y < y + x else 0)))
print(''.join(a))
What is printed?
  1. A. 9534330
  2. B. 9533430
  3. C. 9534303
  4. D. 9543330

Correct answer: A. 9534330

The comparator orders two strings by which concatenation is larger (x+y against y+x), not by numeric value. Sorting by plain numeric value would put 3 and 30 in the wrong order.

More Coding Interview Problems questions

Exams that ask this topic