Largest Number - 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, you need to return a string instead of an integer.

Example: Given [10,2], return "210" (not "102")

Input & Output

Example 1 — Basic Case
$ Input: nums = [10,2]
Output: "210"
💡 Note: Compare arrangements: [10,2] gives "102" vs [2,10] gives "210". Since "210" > "102", return "210".
Example 2 — Multiple Numbers
$ Input: nums = [3,30,34,5,9]
Output: "9534330"
💡 Note: Custom sort compares concatenations: "9"+"5" > "5"+"9", "34"+"3" > "3"+"34", "3"+"30" > "30"+"3", resulting in [9,5,34,3,30] → "9534330".
Example 3 — Edge Case with Zeros
$ Input: nums = [0,0]
Output: "0"
💡 Note: All numbers are zero, so result is "0" (not "00").

Constraints

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Largest Number Problem INPUT Input Array: nums 10 index 0 2 index 1 Problem Goal: Arrange numbers to form the LARGEST possible number as a string Possible Orders: [10, 2] --> "102" [2, 10] --> "210" Which is larger? ALGORITHM STEPS 1 Custom Comparator Compare a+b vs b+a as strings 2 Compare "102" vs "210" "210" > "102", so 2 comes first 3 Sort Array Order: [2, 10] 4 Concatenate Join sorted nums as string Comparison Logic: "10" + "2" = "102" "2" + "10" = "210" "210" > "102" 2 should come before 10 Sorted: [2, 10] FINAL RESULT Sorted Array: 2 10 Concatenate: "2" + "10" OUTPUT: "210" OK - Largest possible! Key Insight: The key to solving this problem is using a custom comparator. Instead of comparing numbers directly, we compare concatenations: for numbers a and b, if (a+b) > (b+a) as strings, then a should come first. Time Complexity: O(n log n) for sorting. Space Complexity: O(n) for the result string. TutorialsPoint - Largest Number | Optimal Solution (Custom Sort)
Asked in
Google 25 Amazon 20 Microsoft 15
185.0K Views
Medium Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen