Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Constructing largest number from an array in JavaScript
We need to write a JavaScript function that takes an array of numbers and arranges them to form the largest possible number by concatenating the digits.
The key insight is that we can't simply sort numbers in descending order. For example, with numbers [3, 30], sorting gives [30, 3] ? "303", but the correct answer is [3, 30] ? "330".
For example ?
If the input array is ?
const arr = [5, 45, 34, 9, 3];
Then the output should be ?
'954543'
Algorithm
The solution uses a custom comparator that checks which concatenation order produces a larger number. For any two numbers a and b, we compare "a+b" vs "b+a" as strings.
Example
Following is the code ?
const arr = [5, 45, 34, 9, 3];
const largestNumber = (arr = []) => {
if(arr.every(n => n === 0)){
return '0';
}
arr.sort((a, b) => {
const s1 = String(a);
const s2 = String(b);
const first = s1 + s2;
const second = s2 + s1;
if(first > second){
return -1;
} else if(first
Output
954543
How It Works
The custom comparator works by:
- Converting numbers to strings
- Comparing "45" + "5" = "455" vs "5" + "45" = "545"
- Since "545" > "455", we place 5 before 45
- This ensures optimal ordering for maximum concatenated value
Edge Cases
// All zeros console.log(largestNumber([0, 0, 0])); // Mixed with zeros console.log(largestNumber([10, 2, 0])); // Single digit numbers console.log(largestNumber([1, 2, 3]));
0 210 321
Conclusion
This approach uses a custom string comparison to determine optimal digit arrangement. The key is comparing concatenated combinations rather than the numbers themselves to achieve the largest possible result.
