Largest Palindromic Number - Problem

Given a string num consisting of digits only, your task is to construct the largest possible palindromic integer using the available digits.

A palindrome reads the same forwards and backwards (like 121, 9339, or 7). You want to create the numerically largest palindrome possible.

Key Rules:

  • You can reorder the digits however you want
  • You don't need to use all digits, but must use at least one
  • No leading zeros allowed (except for the single digit "0")

Examples:

  • Input: "432" → Output: "343" (largest palindrome using available digits)
  • Input: "10" → Output: "1" (can't have leading zero, so just use "1")
  • Input: "00009" → Output: "9" (avoid leading zeros)

Input & Output

example_1.py — Basic Case
$ Input: num = "432"
Output: "343"
💡 Note: We can form palindromes: "4", "3", "2", "343". The largest is "343" using digits 4, 3, 4 (we use 3 in center and 4s on sides).
example_2.py — Leading Zero Case
$ Input: num = "10"
Output: "1"
💡 Note: Possible palindromes: "1", "0". We cannot form "10" or "01" as palindromes. The largest valid palindrome is "1".
example_3.py — Multiple Zeros
$ Input: num = "00009"
Output: "9"
💡 Note: We could form "90009" but this has leading zeros. Valid options are "9", "0". The largest is "9".

Constraints

  • 1 ≤ num.length ≤ 105
  • num consists of only digits
  • Must use at least one digit
  • No leading zeros allowed (except single digit "0")

Visualization

Tap to expand
Building the Perfect Palindromic MirrorExample: "1221" → Build palindrome step by stepMirror LineStep 1: Count tiles1×22×2Step 2: Place pairs (largest first)2112Mirror symmetryResult: "2112" ✓Perfect palindrome using all digits optimally!
Understanding the Visualization
1
Count Your Tiles
Count how many of each digit tile you have available
2
Place Pairs Strategically
Start with largest digits, place pairs symmetrically from outside edges
3
Choose Center Piece
Pick the largest remaining digit for the center position
4
Handle Special Cases
Avoid leading zeros - if result would start with 0, return largest single digit
Key Takeaway
🎯 Key Insight: Palindromes have symmetric structure - we can build them greedily by placing the largest digit pairs first from outside-in, then handling the center and edge cases!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
23.4K Views
Medium Frequency
~18 min Avg. Time
892 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