LeetCode 2384: Largest Palindromic Number Solution

Master LeetCode problem 2384 (Largest Palindromic Number), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2384. Largest Palindromic Number

Problem Explanation

Explanation

To find the largest palindromic number that can be formed using the digits in the input string num, we can follow these steps:

  1. Count the frequency of each digit in the input string.
  2. Construct the largest palindromic number by creating the palindrome from the largest digit to the smallest digit.
  3. Ensure that the number does not have leading zeroes.

The time complexity of this algorithm is O(n) where n is the length of the input string num, and the space complexity is O(1).

Solution Code

import java.util.Arrays;

class Solution {
    public String largestPalindrome(String num) {
        int[] count = new int[10];
        StringBuilder palindrome = new StringBuilder();

        for (char c : num.toCharArray()) {
            count[c - '0']++;
        }

        boolean addedMiddle = false;
        for (int i = 9; i >= 0; i--) {
            if (count[i] > 0) {
                if (!addedMiddle && count[i] % 2 == 1) {
                    palindrome.append(i);
                    count[i]--;
                    addedMiddle = true;
                }
                while (count[i] > 0) {
                    palindrome.insert(0, i);
                    palindrome.append(i);
                    count[i] -= 2;
                }
            }
        }

        return palindrome.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2384 (Largest Palindromic Number)?

This page provides optimized solutions for LeetCode problem 2384 (Largest Palindromic Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2384 (Largest Palindromic Number)?

The time complexity for LeetCode 2384 (Largest Palindromic Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2384 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2384 in Java, C++, or Python.

Back to LeetCode Solutions