179. Largest Number
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The goal is to arrange a list of non-negative integers to form the largest possible number. The result can be very large, so it must be returned as a string. A naive sorting approach, either numerically or lexicographically, will not work. For instance, given [3, 30], 30 is numerically larger than 3, but "330" is larger than "303". This indicates that the relative order of two numbers, say a and b, depends on which combined string, a followed by b (ab) or b followed by a (ba), is larger.
Solution
Largest Number in Python
from functools import cmp_to_key
from typing import List
class Solution:
def largestNumber(self, nums: List[int]) -> str:
# Convert all integers to their string representations.
s_nums = [str(num) for num in nums]
# Define a custom comparison function.
# It returns -1 if `a` should come before `b`.
# `a` should come before `b` if `a+b` forms a larger number than `b+a`.
def compare(a, b):
if a + b > b + a:
return -1 # a is "smaller" and should come first in ascending sort
elif b + a > a + b:
return 1 # b is "smaller"
else:
return 0
# Sort the strings using the custom comparison logic.
# `cmp_to_key` converts a cmp= function to a key= function.
s_nums.sort(key=cmp_to_key(compare))
# If the largest number (the first element after sorting) is "0",
# then all numbers are 0, and the result should be "0".
if s_nums[0] == '0':
return '0'
# Concatenate the sorted strings to get the final largest number.
return "".join(s_nums)
Largest Number in Java
import java.util.Arrays;
import java.util.Comparator;
class Solution {
public String largestNumber(int[] nums) {
// Convert integers to an array of strings.
String[] s_nums = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
s_nums[i] = String.valueOf(nums[i]);
}
// Sort the strings using a custom comparator.
// The comparator (s1, s2) -> (s2 + s1).compareTo(s1 + s2) ensures that
// for any two strings s1 and s2, s1 is placed before s2 if s1+s2 is
// lexicographically larger than s2+s1. This effectively sorts the numbers
// in the desired order to form the largest number.
Arrays.sort(s_nums, (s1, s2) -> (s2 + s1).compareTo(s1 + s2));
// If the largest number (the first element after sorting) is "0",
// then all numbers are 0, and the result should be "0".
if (s_nums[0].equals("0")) {
return "0";
}
// Concatenate the sorted strings to get the final largest number.
StringBuilder sb = new StringBuilder();
for (String s : s_nums) {
sb.append(s);
}
return sb.toString();
}
}
Largest Number in C++
class Solution {
public:
string largestNumber(vector<int>& nums) {
// Convert all integers to their string representations.
vector<string> s_nums;
for (int num : nums) {
s_nums.push_back(to_string(num));
}
// Sort the strings using a custom comparator.
// The comparator arranges 'a' and 'b' such that 'a' comes before 'b'
// if 'a' + 'b' forms a lexicographically larger string than 'b' + 'a'.
sort(s_nums.begin(), s_nums.end(), [](const string& a, const string& b) {
return a + b > b + a;
});
// If the largest number (the first element after sorting) is "0",
// then all numbers must be 0, and the result should be "0".
if (s_nums[0] == "0") {
return "0";
}
// Concatenate the sorted strings to form the largest number.
string result = "";
for (const string& s : s_nums) {
result += s;
}
return result;
}
};
Largest Number in TypeScript
function largestNumber(nums: number[]): string {
// Convert numbers to their string representations.
const s_nums: string[] = nums.map(String);
// Sort strings using a custom comparator.
// We want to arrange 'a' and 'b' such that 'a' comes before 'b'
// if 'a' + 'b' forms a larger number than 'b' + 'a'.
// The sort callback expects a negative value if 'a' should come first.
// `(b + a).localeCompare(a + b)` returns a negative value if `b+a` is
// lexicographically smaller than `a+b`, which is the condition we need.
s_nums.sort((a, b) => (b + a).localeCompare(a + b));
// If the largest number (the first element after sorting) is "0",
// then all numbers are 0, and the result should be "0".
if (s_nums[0] === '0') {
return '0';
}
// Join the sorted strings to get the final largest number.
return s_nums.join('');
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.