Largest Number solution and explanation
9 more videos on this problem
Largest Number - Leetcode 179 - PythonNeetCode · 10:17 · 84K views
largest number | largest number leetcode | leetcode 179 | arrays sort java 8 2 linerNaresh Gupta · 12:00 · 26K views
LeetCode 179. Largest Number [Algorithm + Code Explained ]jayati tiwari · 9:23 · 20K views
179. Largest Number | Top Interview DSA Questions | Java Solution with time complexityShrayansh Jain · 20:17 · 4K views
Largest Number | Leetcode Problem 179 | C++ Solution | SortingThe Tech Coders · 7:50 · 3K views
LARGEST NUMBER | LEETCODE 179 | PYTHON SOLUTIONCracking FAANG · 14:30 · 1K views
LargestNumberVideo179 - Solution to LeetCode 179 Largest NumberLEETCODE MASTER · 8:22 · 464 views
Leetcode 179 - Largest Number JavaScriptChuck's Resume · 8:55 · 362 views
Daily Leetcode #178: Sep 25, 2020 - 179. Largest NumberProgramming Live with Larry · 9:37 · 335 views
Leetcode 179 - Largest NumberData Engineering Studies · 6:49 · 324 views
The problem
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 <= 1000 <= nums[i] <= 109
Approach overview
Problem Overview: You are given an array of non‑negative integers. Rearrange them so that their concatenation forms the largest possible number. The tricky part is that normal numeric sorting does not work. For example, 9 should come before 34, but 34 should come after 3 because 343 is smaller than 334. The solution depends on comparing numbers based on their concatenated order.
Approach 1: Custom Sorting Using Concatenation Comparison (O(n log n))
Convert all integers to strings and sort them using a custom comparator. For two values a and b, compare a + b with b + a. If a + b is larger, a should appear before b in the final ordering. This works because the goal is maximizing the combined string, not the numeric value of each element individually. The algorithm relies on a customized comparison inside a standard sorting routine.
After sorting, concatenate all strings to produce the final number. A special edge case appears when the largest value is "0". This means all numbers are zeros, so return "0" instead of something like "0000". The time complexity is O(n log n) due to sorting, and each comparison costs up to O(k) where k is the digit length. Space complexity is O(n) for storing string representations.
This approach combines ideas from array manipulation and greedy ordering. The greedy insight is that the locally optimal concatenation decision between two numbers leads to a globally optimal result after sorting.
Approach 2: Custom Comparator Using Heap (O(n log n))
Instead of sorting directly, push all numbers (as strings) into a heap that uses the same concatenation comparator rule. The heap ensures that every extraction returns the element that should appear next in the largest concatenated result. Each push and pop operation maintains the comparator order internally.
Repeatedly pop from the heap and append values to the result string. The comparison logic remains identical: choose the element where a + b produces a larger string than b + a. This method still performs about O(n log n) heap operations, and each comparison takes O(k). Space complexity remains O(n) for the heap structure and string storage.
Heap-based ordering is useful if elements are processed incrementally or when you prefer explicit priority queue control instead of full sorting. In most implementations, direct sorting is simpler and faster in practice.
Recommended for interviews: The custom sorting approach is what most interviewers expect. It demonstrates understanding of comparator logic and greedy ordering. Mentioning brute intuition (trying permutations) shows you understand the search space, but implementing the concatenation comparator with a + b vs b + a is the key insight that signals strong problem‑solving skills.
Approach 1: Custom Sorting Using Comparison of Concatenation
This approach involves converting each number to a string and sorting them based on a custom comparator. The key idea is to determine the order of two numbers a and b by comparing the concatenated results a+b and b+a as strings. Sorting the numbers in such a manner ensures that the concatenated string is the largest possible.
from typing import List
def largestNumber(nums: List[int]) -> str:
num_strs = list(map(str, nums))
num_strs.sort(key=lambda x: x*10, reverse=True)
if num_strs[0] == '0':
return '0'
return ''.join(num_strs)
if __name__ == "__main__":
print(largestNumber([3, 30, 34, 5, 9]))import java.util.Arrays;
public class LargestNumber {
public String largestNumber(int[] nums) {
String[] numStrs = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
numStrs[i] = String.valueOf(nums[i]);
}
Arrays.sort(numStrs, (a, b) -> (b + a).compareTo(a + b));
if (numStrs[0].equals("0")) {
return "0";
}
StringBuilder result = new StringBuilder();
for (String numStr : numStrs) {
result.append(numStr);
}
return result.toString();
}
public static void main(String[] args) {
LargestNumber ln = new LargestNumber();
int[] nums = {3, 30, 34, 5, 9};
System.out.println(ln.largestNumber(nums));
}
}#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
string largestNumber(vector<int>& nums) {
vector<string> numStrs;
for (int num : nums) {
numStrs.push_back(to_string(num));
}
sort(numStrs.begin(), numStrs.end(), [](const string& a, const string& b) {
return a + b > b + a;
});
if (numStrs[0] == "0") {
return "0";
}
string result;
for (const string& numStr : numStrs) {
result += numStr;
}
return result;
}
int main() {
vector<int> nums = {3, 30, 34, 5, 9};
cout << largestNumber(nums) << endl;
return 0;
}function largestNumber(nums) {
nums.sort((a, b) => ('' + b + a) - ('' + a + b));
if (nums[0] === 0) return '0';
return nums.join('');
}
console.log(largestNumber([3, 30, 34, 5, 9]));#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b) {
char *num1 = *(char **)a;
char *num2 = *(char **)b;
char option1[20], option2[20];
sprintf(option1, "%s%s", num1, num2);
sprintf(option2, "%s%s", num2, num1);
return strcmp(option2, option1);
}
char* largestNumber(int* nums, int numsSize) {
char* numsStr[numsSize];
for (int i = 0; i < numsSize; i++) {
numsStr[i] = malloc(11);
sprintf(numsStr[i], "%d", nums[i]);
}
qsort(numsStr, numsSize, sizeof(char*), compare);
if (numsStr[0][0] == '0') {
return "0";
}
int totalLength = 0;
for (int i = 0; i < numsSize; i++) {
totalLength += strlen(numsStr[i]);
}
char* result = malloc(totalLength + 1);
result[0] = '\0';
for (int i = 0; i < numsSize; i++) {
strcat(result, numsStr[i]);
free(numsStr[i]);
}
return result;
}
int main() {
int nums[] = {3, 30, 34, 5, 9};
int size = sizeof(nums) / sizeof(nums[0]);
char* result = largestNumber(nums, size);
printf("%s\n", result);
free(result);
return 0;
}using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public string LargestNumber(int[] nums) {
var numStrs = nums.Select(num => num.ToString()).ToArray();
Array.Sort(numStrs, (a, b) => string.Compare(b + a, a + b));
if (numStrs[0] == "0") {
return "0";
}
return string.Concat(numStrs);
}
public static void Main(string[] args) {
Solution sol = new Solution();
Console.WriteLine(sol.LargestNumber(new int[] {3, 30, 34, 5, 9}));
}
}This solution converts the numbers to strings and sorts them using a custom sort order, defined by a lambda function. The sorting logic entails repeating the string to ensure comparison length is sufficient. After sorting, strings are concatenated to form the result.
Time Complexity: O(n log n), due to the sorting of strings.
Space Complexity: O(n) for the string representations of numbers.
Approach 2: Custom Comparator Using Heap
This approach involves using a custom comparator with a min-heap to continuously extract the largest possible number combination. This can be more efficient in some cases where we require efficient access to the largest current element for concatenation.
import heapq
def largestNumber(nums):
if not nums:
return ''
nums_str = list(map(str, nums))
heap = [(-1 * int(num * 10), num) for num in nums_str]
heapq.heapify(heap)
if heap[0][1] == '0':
return '0'
result = ''
while heap:
result += heapq.heappop(heap)[1]
return result
print(largestNumber([3, 30, 34, 5, 9]))The solution uses a max-heap implemented with negative values in Python’s built-in heapq, to facilitate priority retrieval of the ‘largest’ lexical integer string. The heap ensures the largest value is popped and concatenated first.
Time Complexity: O(n log n), dominated by the heap operations.
Space Complexity: O(n) due to the heap storage.
Approach 3: Default Approach
function largestNumber(nums: number[]): string {
nums.sort((a, b) => {
const [ab, ba] = [String(a) + String(b), String(b) + String(a)];
return +ba - +ab;
});
return nums[0] ? nums.join('') : '0';
}func largestNumber(nums []int) string {
vs := make([]string, len(nums))
for i, v := range nums {
vs[i] = strconv.Itoa(v)
}
sort.Slice(vs, func(i, j int) bool {
return vs[i]+vs[j] > vs[j]+vs[i]
})
if vs[0] == "0" {
return "0"
}
return strings.Join(vs, "")
}Complexity comparison
| Approach | Complexity |
|---|---|
| Custom Sorting Using Comparison of Concatenation | Time Complexity: O(n log n), due to the sorting of strings. |
| Custom Comparator Using Heap | Time Complexity: O(n log n), dominated by the heap operations. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Custom Sorting with Concatenation Comparator | O(n log n * k) | O(n) | General solution; simplest and most common interview implementation |
| Heap with Custom Comparator | O(n log n * k) | O(n) | When elements arrive incrementally or priority queue ordering is preferred |
Frequently asked questions
Is Largest Number easy or hard?
Largest Number is generally considered a medium difficulty problem. The implementation is short once you know the trick, but discovering the correct comparison rule a+b vs b+a requires careful reasoning about string ordering and greedy decisions.
Largest Number Python/Java solution
Python solutions typically use sorted() with functools.cmp_to_key to implement the custom comparator. Java implementations use Arrays.sort with a Comparator that compares (b + a) and (a + b). Both versions follow the same greedy ordering logic and run in O(n log n) time.
How to solve Largest Number in O(n)?
An exact O(n) solution is not practical because the problem requires ordering elements relative to each other. Any comparison-based ordering requires at least O(n log n) operations. The optimal practical approach is sorting with a custom comparator that compares a+b and b+a.
What is the best approach for Largest Number?
The best approach uses custom sorting with a concatenation comparator. Convert numbers to strings and compare a+b with b+a to decide ordering. Sorting with this rule ensures the final concatenation produces the largest possible number. The overall time complexity is O(n log n * k), where k is the average digit length.
Is Largest Number asked at Google/Amazon/Meta?
Largest Number is a common medium-level interview problem seen in companies like Amazon, Google, and Meta. It tests understanding of custom comparators, greedy ordering logic, and edge cases with string concatenation. Interviewers often expect candidates to derive the a+b vs b+a comparison insight.
What data structure is used in Largest Number?
The primary data structure is an array of strings combined with a custom sorting comparator. Some implementations also use a heap or priority queue with the same comparator rule. The key idea is comparing concatenated strings rather than numeric values.
What is the time complexity of Largest Number?
The optimal solution runs in O(n log n * k) time. The n log n factor comes from sorting the array, while k represents the cost of comparing concatenated strings during the custom comparator check. Space complexity is O(n) because the integers are typically converted into strings.
