#179
Medium Algorithms Largest number
Array String Greedy Sorting
42.6% acceptance
Jan 12, 2026
9420
800
Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn largest_number(nums: Vec<i32>) -> String {
let mut nums_str: Vec<String> = nums.iter().map(|n| n.to_string()).collect();
nums_str.sort_by(|a, b| {
let ab = format!("{}{}", a, b);
let ba = format!("{}{}", b, a);
ba.cmp(&ab)
});
if nums_str[0] == "0" {
return "0".to_string();
}
nums_str.concat()
}
}