Skip to main content

Largest Number - Solution & Explanation

MediumArrayStringGreedySorting11 min readAsked at: Amazon, Microsoft, Goldman Sachs +20
Practice this problem

Problem Statement

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] <= 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.

This solution first converts each number to a string and stores it in an array. It then sorts the array using a custom comparator. The comparator function forms two possible concatenated strings and orders based on which string is larger. After sorting, it concatenates the sorted numbers to form the largest number and checks for leading zeros.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n), where n is the number of elements, due to sorting. Comparison operation within the sort is O(1) as it's based on string concatenation and comparison.
Space Complexity: O(n), where n is the number of integers, due to the storage of string representations of integers.

Try this approach in the editor →

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.

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.

Code

Python

Complexity

Time Complexity: O(n log n), dominated by the heap operations.
Space Complexity: O(n) due to the heap storage.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

C#

TypeScript

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Custom Sorting Using Comparison of Concatenation

Time Complexity: O(n log n), where n is the number of elements, due to sorting. Comparison operation within the sort is O(1) as it's based on string concatenation and comparison.
Space Complexity: O(n), where n is the number of integers, due to the storage of string representations of integers.

Custom Comparator Using Heap

Time Complexity: O(n log n), dominated by the heap operations.
Space Complexity: O(n) due to the heap storage.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Custom Sorting with Concatenation ComparatorO(n log n * k)O(n)General solution; simplest and most common interview implementation
Heap with Custom ComparatorO(n log n * k)O(n)When elements arrive incrementally or priority queue ordering is preferred

Video Solution

Largest Number - Leetcode 179 - Python • NeetCode • 84,814 views views

Watch 9 more video solutions →

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.

Ready to solve this problem?

Practice Largest Number with our built-in code editor and test cases.

Practice on FleetCode