Largest Palindromic Number

Build the largest palindrome from given digits using greedy half-construction.

Medium
Time O(n) Space O(1)
LeetCode
5 min read
greedy string

Problem#

Given a string of digits, return the largest palindrome you can build using any subset (no leading zeros unless the whole result is “0”).

Examples#

  • "444947137""7449447"
  • "00009""9"

Constraints#

  • 1 <= n <= 10^5.

Hints#

Hint 1
Count each digit. For each pair, append digit to a “half” string. Pick the largest unused digit as the optional middle character.

Approach#

Count digits 0–9. Build the left half: walk digits 9..0; while count ≥ 2, append a digit and consume 2. Pick the optional middle: largest digit with remaining count > 0. Watch for the all-zero leading-zero case.

Solution#

Largest Palindromic Number
class Solution {
public:
string largestPalindromic(string num) {
int cnt[10] = {0};
for (char c : num) ++cnt[c - '0'];
string half;
for (int d = 9; d >= 0; --d) {
while (cnt[d] >= 2) {
if (half.empty() && d == 0) break; // avoid leading zeros
half += '0' + d;
cnt[d] -= 2;
}
if (half.empty() && d == 0) break;
}
int mid = -1;
for (int d = 9; d >= 0; --d) if (cnt[d] > 0) { mid = d; break; }
string ans = half;
if (mid >= 0) ans += '0' + mid;
ans += string(half.rbegin(), half.rend());
return ans.empty() ? "0" : ans;
}
};

Editorial#

A palindrome’s left half determines its order. Greedy: at each digit slot, take the largest available pair. The leading-zero rule prevents 00...x...00 outputs. The middle character is the largest single digit remaining after all pairs are placed.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.