Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Arrange non-negative integers so that their concatenation forms the largest number (returned as a string). Sort with the comparator 'a before b if a + b > b + a'.

Problem: Arrange non-negative integers so that their concatenation forms the largest number (returned as a string). Sort with the comparator 'a before b if a + b > b + a'.
from functools import cmp_to_key
def largest(nums):
    s = sorted(map(str, nums), key=cmp_to_key(lambda a, b: (b + a > a + b) - (b + a < a + b)))
    r = "".join(s)
    return "0" if r[0] == "0" else r
print(largest([7, 50, 5, 56, 4]), largest([0, 0]), largest([8, 89, 898]))
What is printed?
  1. A. 7565504 0 898898
  2. B. 7565504 0 898988
  3. C. 7565054 0 898898
  4. D. 7565504 00 898988

Correct answer: B. 7565504 0 898988

The pairwise rule 'a + b > b + a' is a valid total order, and sorting by it gives the optimum. 5 vs 50: "550" > "505", so 5 first; 56 vs 5: "565" > "556", so 56 first → 7 56 5 50 4. Plain reverse string sorting puts 50 before 5 ("7565054") and 898 before 89 ("898898" < "898988"). All zeros must collapse to "0". O(n log n · L).

More Coding Interview Problems questions

Exams that ask this topic