githubEdit

20. Form the Largest Number

βœ… GFG solution to Form the Largest Number: arrange numbers to create the largest possible concatenated value using custom comparator sorting. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

Given an array of integers arr[] representing non-negative integers, arrange them so that after concatenating all of them in order, it results in the largest possible number. Since the result may be very large, return it as a string.

πŸ“˜ Examples

Example 1

Input: arr[] = [3, 30, 34, 5, 9]
Output: "9534330"
Explanation: Given numbers are [3, 30, 34, 5, 9], the arrangement [9, 5, 34, 3, 30] 
gives the largest value.

Example 2

Input: arr[] = [54, 546, 548, 60]
Output: "6054854654"
Explanation: Given numbers are [54, 546, 548, 60], the arrangement [60, 548, 546, 54] 
gives the largest value.

Example 3

πŸ”’ Constraints

  • $1 \le \text{arr.size()} \le 10^5$

  • $0 \le \text{arr}[i] \le 10^5$

βœ… My Approach

The solution uses a Custom Comparator with Greedy Sorting:

Custom Comparator Sorting

  1. Key Insight:

    • To determine if number a should come before b, compare the concatenations: ab vs ba.

    • If ab > ba lexicographically, then a should come before b.

    • Example: For 3 and 30, compare "330" vs "303" β†’ "330" > "303", so 3 comes before 30.

  2. Convert to Strings:

    • Convert all integers to strings for easy concatenation and comparison.

  3. Sort with Custom Comparator:

    • Sort the string array using a comparator that compares s1+s2 with s2+s1.

    • Sort in descending order to get larger combinations first.

  4. Handle Edge Case:

    • If the first element after sorting is "0", all elements are zeros.

    • Return "0" instead of "000...".

  5. Concatenate Result:

    • Join all sorted strings to form the final largest number.

Why This Works: The custom comparator ensures transitivity. If a should come before b and b before c, then a comes before c, making the sorting valid and optimal.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n log n), where n is the size of the array. The dominant operation is sorting with a custom comparator, which takes O(n log n) comparisons. Each comparison involves string concatenation and comparison, which takes O(k) where k is the average number of digits, but this is constant for the given constraints (max 5 digits).

  • Expected Auxiliary Space Complexity: O(n), as we create an array of n strings to store the string representations of the numbers. The concatenation result also uses O(n*k) space where k is the average length of numbers.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Static Comparator Function

πŸ’‘ Algorithm Steps:

  1. Define a static comparison function outside the class or as a static member.

  2. Convert all integers to strings for comparison.

  3. Sort using the custom comparator that compares concatenated results.

  4. Handle the all-zeros edge case by checking the first element.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log n) - Sorting dominates

  • Auxiliary Space: πŸ’Ύ O(n) - String array storage

βœ… Why This Approach?

  • Clear separation with named comparator function

  • Easier to debug and test comparator independently

  • More readable for those unfamiliar with lambdas

πŸ“Š 3️⃣ In-Place String Building

πŸ’‘ Algorithm Steps:

  1. Convert numbers to strings and store in vector.

  2. Use custom comparator for sorting.

  3. Build result string incrementally without separate loop.

  4. Optimize by using string reserve for better performance.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log n) - Sort operation

  • Auxiliary Space: πŸ’Ύ O(n) - Vector of strings

βœ… Why This Approach?

  • Uses const references for better performance

  • Reserve optimization reduces reallocations

  • Professional code style

πŸ“Š 4️⃣ Direct Integer Comparison (Alternative Logic)

πŸ’‘ Algorithm Steps:

  1. Keep numbers as integers initially.

  2. Convert to strings only during comparison.

  3. Sort using inline comparator with on-the-fly conversion.

  4. Build final string from sorted integers.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log n) - Sorting with string operations

  • Auxiliary Space: πŸ’Ύ O(1) - Sorts in-place (excluding output)

βœ… Why This Approach?

  • Minimal auxiliary space before final result

  • Sorts original array in-place

  • Reduces initial memory allocation

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🎯 Lambda Comparator

🟒 O(n log n)

🟑 O(n)

πŸš€ Concise, modern C++

πŸ”§ Lambda overhead (minimal)

πŸ”„ Static Comparator

🟒 O(n log n)

🟑 O(n)

πŸ“– Clear, debuggable

πŸ”§ More verbose

πŸ“Š In-Place Building

🟒 O(n log n)

🟑 O(n)

⚑ Optimized with reserve

πŸ”§ Similar to main approach

πŸ”’ Direct Integer Sort

🟒 O(n log n)

🟒 O(1)*

πŸ’Ύ Space efficient

πŸ”§ Repeated to_string calls

*Excluding output string

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Competitive programming

πŸ₯‡ Lambda Comparator

β˜…β˜…β˜…β˜…β˜…

πŸ“– Interview clarity

πŸ₯ˆ Static Comparator

β˜…β˜…β˜…β˜…β˜…

πŸ’Ύ Memory constrained

πŸ₯‰ Direct Integer Sort

β˜…β˜…β˜…β˜…β˜†

πŸ”§ Production code

πŸ… In-Place Building

β˜…β˜…β˜…β˜…β˜…

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated