I was trying out leetcode's Largest Number.
As per the challenge's description:
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\$
Here is my solution:
class Solution {
// custom comparator: comparing integers as strings
// to decide which to place before the other.
static class SortByFirstDigit implements Comparator<Integer> {
@Override
public int compare(Integer i1, Integer i2) {
String a = Integer.toString(i1);
String b = Integer.toString(i2);
//compare integers as strings to know which will be picked up ie 'ab' and 'ba' for example
return Integer.compare(0, (a + b).compareTo(b + a));
}
}
// REF: Convert int[] to Integer[]
// function toConvertInteger is taken from stackoverflow at:
// https://stackoverflow.com/a/31967630/1063062
public static Integer[] toConvertInteger(int[] ids) {
Integer[] newArray = new Integer[ids.length];
for (int i = 0; i < ids.length; i++) {
newArray[i] = Integer.valueOf(ids[i]);
}
return newArray;
}
public String largestNumber(int[] nums) {
Integer[] Nums = toConvertInteger(nums);
Arrays.sort(Nums, new SortByFirstDigit());
StringBuilder builder = new StringBuilder();
for (int s : Nums) builder.append(s);
//if we get a string of all zeros, strip to 1 zero.
if (builder.toString().matches("^[0]+$")) return "0";
return builder.toString();
}
}
Question
- This code passes all test but runs in around 9ms. What part(s) of the code are making it slow? and how to make it faster?
- Or, is it better to solve this problem in other ways (ie more performant) like for example using a N-ary tree for example? While analyzing the problem I had at some point thought of a tree algorithm which I will explain graphically in this picture:
It will traverse from leafs to parents following:
concatenate(parent key + greater integer nodes (ie greater than parent)) ---> parent integer value --> concatenate (parent key + smaller integer nodes (ie smaller than parent))
ie in this example 9 5 34 3 30
"9"
) sorting before long ones (e.g."91"
) helps us quickly find the answer. The example highlights"2" > "10"
. \$\endgroup\$