16. Form the Largest Number
β GFG solution to the Form the Largest Number problem: arrange integers to form the largest possible number using custom comparator sorting technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an array arr[]
of non-negative integers. Your task is to arrange them so that after concatenating all of them in order, it results in the largest possible number. Since the result may be very large, return it as a string.
The key insight is that we need to sort the numbers based on which arrangement produces a larger concatenated result, not by their numerical values.
π Examples
Example 1
Input: arr[] = [3, 30, 34, 5, 9]
Output: "9534330"
Explanation: Given numbers are [3, 30, 34, 5, 9], the arrangement [9, 5, 34, 3, 30]
gives the largest value.
Example 2
Input: arr[] = [54, 546, 548, 60]
Output: "6054854654"
Explanation: Given numbers are [54, 546, 548, 60], the arrangement [60, 548, 546, 54]
gives the largest value.
Example 3
Input: arr[] = [3, 4, 6, 5, 9]
Output: "96543"
Explanation: Given numbers are [3, 4, 6, 5, 9], the arrangement [9, 6, 5, 4, 3]
gives the largest value.
π Constraints
$1 \le \text{arr.size()} \le 10^5$
$0 \le \text{arr}[i] \le 10^5$
β
My Approach
The optimal approach uses Custom Comparator Sorting with String Concatenation to determine the correct order:
Custom Comparator + String Sorting
Convert to Strings:
Convert all integers to strings for easy concatenation comparison.
This allows us to compare concatenated results directly.
Custom Comparator Logic:
For any two numbers
a
andb
, comparea+b
vsb+a
(concatenation).If
a+b > b+a
, thena
should come beforeb
in the final arrangement.This ensures optimal ordering for maximum result.
Sort with Comparator:
Use the custom comparator to sort the string array.
The comparator function:
(x + y > y + x)
determines order.
Handle Edge Case:
If the largest number is "0", return "0" (handles arrays like [0, 0, 0]).
This prevents returning "000" instead of "0".
Build Result:
Concatenate all sorted strings to form the final result.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n log n Γ k), where n is the number of elements and k is the average number of digits per number. The sorting takes O(n log n) comparisons, and each comparison involves string operations that take O(k) time.
Expected Auxiliary Space Complexity: O(n Γ k), where we store n strings each of average length k. The sorting algorithm may use additional O(log n) space for recursion stack.
π§βπ» Code (C++)
class Solution {
public:
string findLargest(vector<int>& arr) {
vector<string> s;
for (int x : arr) s.push_back(to_string(x));
sort(s.begin(), s.end(), [](const string& x, const string& y) {
return x + y > y + x;
});
if (s[0] == "0") return "0";
string result;
for (const string& str : s) result += str;
return result;
}
};
β Code (Java)
class Solution {
public String findLargest(int[] arr) {
String[] s = new String[arr.length];
for (int i = 0; i < arr.length; i++) s[i] = String.valueOf(arr[i]);
Arrays.sort(s, (x, y) -> (x + y).compareTo(y + x) > 0 ? -1 : 1);
if (s[0].equals("0")) return "0";
StringBuilder res = new StringBuilder();
Arrays.stream(s).forEach(res::append);
return res.toString();
}
}
π Code (Python)
class Solution:
def findLargest(self, arr):
s = sorted(map(str, arr), key=cmp_to_key(lambda x, y: -1 if x + y > y + x else 1))
return '0' if s[0] == '0' else ''.join(s)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated