โ† Back to Index

๐Ÿ“š Largest Palindromic Number โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Largest Palindromic Number problem involves constructing the largest palindromic number possible using the digits from a given string. A palindromic number reads the same backward as forward.

๐Ÿงฑ Pattern Template

Greedy Algorithm with Frequency Count

class Solution {
    public String largestPalindromicNumber(String num) {
        int[] count = new int[10];
        for (char c : num.toCharArray()) {
            count[c - '0']++;
        }

        StringBuilder half = new StringBuilder();
        char middle = 0;

        // Build the largest half of the palindrome
        for (int i = 9; i >= 0; i--) {
            while (count[i] >= 2) {
                // Avoid leading zeroes in the palindrome
                if (half.length() == 0 && i == 0) break;
                half.append(i);
                count[i] -= 2;
            }
            // Check for a middle digit
            if (count[i] > 0 && middle == 0) {
                middle = (char) (i + '0');
            }
        }

        // Handle edge case: If no valid palindrome can be formed
        if (half.length() == 0 && middle == 0) return "0";

        // Construct the full palindrome
        String halfStr = half.toString();
        return middle == 0 ? halfStr + half.reverse() : halfStr + middle + half.reverse();
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example

Input: num = "98231256"
Output: "292"

Explanation:
- Use digits [2, 9, 2] to form the largest palindrome: "292".

๐Ÿ’ก Pro Tips