Breaking down today's GFG POTD — simply.
Form the Largest Number
Input: arr[] = [3, 30, 34, 5, 9]
Intro: The naive way would be to sort by value — but that doesn't work here. 9 should come before 54 even though 54 is bigger, because 954 > 549. We need a smarter comparison.
Convert all integers to strings so we can compare by concatenation
Sort using a custom comparator — for A and B, compare AB vs BA as strings. Whichever is bigger goes first.
Join everything together into one final string
Edge case — if result starts with "0", return "0"
class Solution:
def findLargest(self, arr):
from functools import cmp_to_key
arr = [str(x) for x in arr]
def compare(a, b):
if a + b > b + a:
return -1
elif a + b < b + a:
return 1
return 0
arr.sort(key=cmp_to_key(compare))
result = "".join(arr)
return "0" if result[0] == "0" else resultclass Solution {
public String findLargest(int[] arr) {
String[] strArr = new String[arr.length];
for (int i = 0; i < arr.length; i++)
strArr[i] = String.valueOf(arr[i]);
Arrays.sort(strArr, (a, b) -> (b + a).compareTo(a + b));
if (strArr[0].equals("0")) return "0";
StringBuilder result = new StringBuilder();
for (String s : strArr) result.append(s);
return result.toString();
}
}class Solution {
public:
string findLargest(vector<int> &arr) {
vector<string> strArr;
for (int x : arr) strArr.push_back(to_string(x));
sort(strArr.begin(), strArr.end(), [](string& a, string& b) {
return (a + b) > (b + a);
});
if (strArr[0] == "0") return "0";
string result = "";
for (string& s : strArr) result += s;
return result;
}
};Sorting with custom comparator
Storing string converted array
Sometimes the comparison logic itself IS the entire solution. Before sorting, always ask — am I comparing the right thing? Sorting by value and sorting by impact are two very different things!
Follow along with the 60 Days POTD · NPCI × GeeksforGeeks — daily solutions and breakdowns.