Skip to main content

Largest Number


Largest Number: 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.

Example 1:
Input: nums = [10,2]
Output: "210"

Example 2:
Input: nums = [3,30,34,5,9]
Output: "9534330"
Constraints:
  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 10^9

Try this Problem on your own or check similar problems:

  1. Smallest Value of the Rearranged Number
Solution:
public String largestNumber(int[] nums) {
StringBuilder sb = new StringBuilder();

nums = Arrays.stream(nums).boxed().sorted((a, b) -> {
String valA = String.valueOf(a), valB = String.valueOf(b);
String o1 = valA + valB, o2 = valB + valA;
return o2.compareTo(o1);
}).mapToInt(Integer::intValue).toArray();

if(nums.length == 0 || nums[0] == 0) return "0";
for(int num: nums) sb.append(num);
return sb.toString();
}

Time/Space Complexity:
  • Time Complexity: O(nlogn)
  • Space Complexity: O(1)

Explanation:

We're converting the number to the string in custom comparison function but note that we have constant time/space complexity since the number of digits in a number is bound by the highest number by problem statement 10^9. To achieve the largest number, we sort the array using the lambda expression which compares two integers by concatenating their string representation in both order and then comparing their lexicographic order. This will sort the integers in descending order based on the lexicographic order of their concatenated string representations. If the largest number is still 0 after sorting, we return "0" otherwise we build the string in the decreasing order of elements in sorted array. Time complexity is governed by the sorting operation which is O(nlogn) (where n is the number of elements in the input array).