Skip to content

Sorting with a custom comparator [ref]

Problem

  • Sort ["3", "30", "34"] by which concatenation produces the larger number.
  • Compare wrapped "3" and "30" after converting that comparator with cmp_to_key.
  • Join the sorted strings into their largest concatenation.

Python solution

from functools import cmp_to_key

def compare(a, b):
    if a + b > b + a:
        return -1
    if a + b < b + a:
        return 1
    return 0

parts = sorted(["3", "30", "34"], key=cmp_to_key(compare))
parts  # ['34', '3', '30']

key = cmp_to_key(compare)
key("3") < key("30")  # True

"".join(parts)  # '34330'