179. Largest Number
Asked at 17Amazon50Microsoft44Bloomberg42Google40Meta36josh technology100Infosys50Nykaa100Works Applications100Zoho83Adobe63ServiceNow55Accenture44Nvidia39Oracle35TikTok35Goldman Sachs28
Problem
Arrange the non-negative integers in nums so that concatenating them forms the largest possible number, and return it as a string (no leading zeros, so all zeros give "0").
Example: [3,30,34,5,9] → "9534330"
Sort strings with the comparator "a before b if a + b > b + a". This ordering is transitive, so the concatenation is maximal. Edge case: all zeros → "0".
Complexity: O(n log n · L).
class Solution:
def largestNumber(self, nums: List[int]) -> str:
s = sorted(map(str, nums), key=functools.cmp_to_key(lambda a, b: -1 if a + b > b + a else 1))
res = "".join(s)
return "0" if res[0] == "0" else res
assert Solution().largestNumber([10, 2]) == "210"
assert Solution().largestNumber([3, 30, 34, 5, 9]) == "9534330"
assert Solution().largestNumber([0, 0]) == "0"
class Solution {
public String largestNumber(int[] nums) {
String[] s = Arrays.stream(nums).mapToObj(String::valueOf).toArray(String[]::new);
Arrays.sort(s, (a, b) -> (b + a).compareTo(a + b));
if (s[0].equals("0")) return "0";
return String.join("", s);
}
}
func largestNumber(nums []int) string {
s := make([]string, len(nums))
for i, x := range nums {
s[i] = strconv.Itoa(x)
}
sort.Slice(s, func(i, j int) bool { return s[i]+s[j] > s[j]+s[i] })
if s[0] == "0" {
return "0"
}
return strings.Join(s, "")
}