Leetcode Largest Number problem solution YASH PAL, 31 July 2024 In this Leetcode Largest Number problem solution we have given a list of non-negative integers nums, arrange them such that they form the largest number. Problem solution in Python. def largestNumber(self, nums): numstr = sorted([str(num) for num in nums]) curr = [numstr[0]] for i in range(1, len(nums)): if curr[-1] +numstr[i] > numstr[i]+curr[-1]: numstr[i-len(curr)] = numstr[i] numstr[i] = curr[-1] elif curr[-1] +numstr[i] == numstr[i]+curr[-1]: curr.append(numstr[i]) else: curr = [numstr[i]] result = ''.join(reversed(numstr)) if int(result)>0: return result else: return '0' Problem solution in Java. public class Solution { public String largestNumber(int[] nums) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(nums.length, new Comparator<Integer>(){ public int compare(Integer a,Integer b){ String num1 = String.valueOf(a)+String.valueOf(b); String num2 = String.valueOf(b)+String.valueOf(a); return num2.compareTo(num1); } }); for (int a : nums) pq.offer(a); String res=""; while(!pq.isEmpty()) res+=pq.poll(); if(res.charAt(0)=='0') return "0"; return res; } } Problem solution in C++. static bool comparator(string a, string b) { return (a+b) > (b+a); } string largestNumber(vector<int>& nums) { vector<string> v; for(int i = 0; i < nums.size(); i++) v.push_back(to_string(nums[i])); sort(v.begin(), v.end(), comparator); string s = ""; for(int i = 0; i < v.size(); i++) s += v[i]; while(s.size() > 1 && s[0] == '0') s.erase(s.begin()); return s; } Problem solution in C. int compare(const void* a, const void* b) { const char** ia = (const char*)a; const char** ib = (const char*)b; char* string1[20] = { ' ' }; char* string2[20] = { ' ' }; strcat(string1, *ia); strcat(string1, *ib); strcat(string2, *ib); strcat(string2, *ia); return -1*strcmp(string1, string2); } char * largestNumber(int* nums, int numsSize){ char* zero = "0"; char** temp = malloc(sizeof(char*) * numsSize); for (int i = 0; i < numsSize; i++) { temp[i] = malloc(sizeof(char) * 10); sprintf(temp[i], "%d", nums[i]); } qsort(temp, numsSize, sizeof(char*) , compare); if (!strcmp(temp[0], "0")) { return "0"; } char* ans = malloc(sizeof(char) * 500); ans[0] = ' '; for (int i = 0; i < numsSize; i++) { strcat(ans, temp[i]); } printf("%s", ans); return ans; } coding problems