Form the Maximum Number from Array Elements

viaGlassdoor

Problem: Given an array of non-negative integers, arrange them so that they form the largest possible number when concatenated together.

Constraints: Array elements are non-negative integers of varying digit lengths.

Example: [3, 30, 34, 5, 9] -> largest number = "9534330".

Approach: Define a custom comparator that, for two numbers a and b, compares the concatenations (a+b) vs (b+a) as strings and orders a before b if (a+b) > (b+a). Sort the array using this comparator, then concatenate in sorted order. O(n log n) time.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account