Largest Palindromic Number - Problem

You are given a string num consisting of digits only.

Return the largest palindromic integer (in the form of a string) that can be formed using digits taken from num. It should not contain leading zeroes.

Notes:

  • You do not need to use all the digits of num, but you must use at least one digit.
  • The digits can be reordered.

Input & Output

Example 1 — Basic Case
$ Input: num = "432"
Output: "4"
💡 Note: We can form palindromes: "4", "3", "2". The largest is "4".
Example 2 — Multiple Digits
$ Input: num = "432132"
Output: "432234"
💡 Note: Count: 4×1, 3×2, 2×2, 1×1. Build first half with pairs: "43", middle: "2", result: "432" + "2" + "234" = "432234".
Example 3 — Leading Zero Edge Case
$ Input: num = "10"
Output: "1"
💡 Note: Cannot form "101" due to no leading zeros rule. Best palindrome using available digits is "1".

Constraints

  • 1 ≤ num.length ≤ 105
  • num consists of digits only

Visualization

Tap to expand
Largest Palindromic Number INPUT String num = "432" '4' '3' '2' Digit Frequency Digit Count 2 1 3 1 4 1 All counts = 1 (no pairs available) ALGORITHM STEPS 1 Count Digits Build frequency map for digits 0-9 2 Build Palindrome Half Iterate 9 to 0, add pairs No pairs found here! 3 Find Middle Digit Pick largest odd-count digit: 4 > 3 > 2 4 -- Selected! 4 Handle Edge Cases Check leading zeros Empty half? Use middle Greedy: Pick largest first FINAL RESULT Building Palindrome: "" Left half "4" Middle "" Right half Combine: "" + "4" + "" = "4" Output: "4" OK - Valid Palindrome 4 reads same forwards and backwards Key Insight: For palindromes, we need PAIRS of digits for left/right halves. Only ONE odd-count digit can be the middle. When no pairs exist (all counts=1), the largest single digit IS the answer. Greedy approach: always pick largest available digits first to maximize the result. TutorialsPoint - Largest Palindromic Number | Optimized Greedy with Edge Case Handling
Asked in
Google 25 Amazon 18 Facebook 15 Microsoft 12
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen