DDSA Solutions

Form the Largest Number

Advertisement

Intuition

Custom sort: compare pairs of numbers by which concatenation is larger (ab vs ba as strings).

Algorithm

  1. 1Convert numbers to strings.
  2. 2Sort with comparator: a+b vs b+a (string concatenation comparison).
  3. 3Concatenate. Edge case: if result starts with 0, return "0".

Common Pitfalls

  • Edge case: all zeros -> return "0". Comparator must compare concatenation strings, not individual values.
Form the Largest Number.java
Java
// Approach: Custom sort: compare 'ab' vs 'ba' as strings. Concatenate sorted numbers for maximum result.
// Time: O(n log n * digits) Space: O(n)
import java.util.*;

class Solution {
    public String findLargest(int[] arr) {
        int n = arr.length;
        String[] nums = new String[n];

        for (int i = 0; i < n; i++)
            nums[i] = Integer.toString(arr[i]);

        Arrays.sort(nums, (a, b) -> (b + a).compareTo(a + b));

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++)
            sb.append(nums[i]);

        String ans = sb.toString();
        if (ans.charAt(0) == '0')
            return "0";

        return ans;
    }
}
Advertisement
Was this solution helpful?