we are comparing the concactenation of numbers not their addition. so the numbers are turned to strings and are sorted based on their concactenation in descending order and are then joined an returned.
-
Time complexity:O(N log N)
-
Space complexity:O(N)
function largestNumber(nums: number[]): string {
const result = nums
.map(String)
.sort((a, b) => {
return a.concat(b) > b.concat(a) ? -1 : 1;
})
.join('');
return result.charAt(0) === '0' ? '0' : result;
};