179. Largest Number

 

Intuition

The main idea behind this code is to arrange a list of non-negative integers in such a way that, when concatenated, they form the largest possible number.

Approach

Convert Integers to Strings:

First, convert each integer in the array to a string and store these strings in a new array.

Custom Sorting:

Sort the array of strings using a custom comparator. The comparator defines the order based on the concatenated result of two strings in both possible orders. This ensures that the concatenation of the strings results in the largest possible number.

Build the Result:

After sorting, concatenate the sorted strings to form the final result.

Handle Edge Case:

If the largest number is 0 (which means all numbers were 0), return "0" instead of multiple zeros.

Complexity

  • Time complexity: O(NLogN)
  • Space complexity: O(N)

Code

Java
class Solution {
    public String largestNumber(int[] nums) {
        String[] numStringArr = new String[nums.length];
        for(int i = 0; i < nums.length; i++) {
            numStringArr[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(numStringArr, (a, b)-> (b + a).compareTo(a + b));
        StringBuilder result = new StringBuilder();
        for(int i = 0; i < numStringArr.length; i++) {
            result.append(numStringArr[i]);
        }
        return result.charAt(0) == '0' ? "0" : result.toString();
    }
}

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

LeetCode Problem: Implement pow(x, n) leetcode:- 50