Largest Palindromic Number Problem
Description
LeetCode Problem 2384.
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.
Example 1:
Input: num = "444947137"
Output: "7449447"
Explanation:
Use the digits "4449477" from "444947137" to form the palindromic integer "7449447".
It can be shown that "7449447" is the largest palindromic integer that can be formed.
Example 2:
Input: num = "00009"
Output: "9"
Explanation:
It can be shown that "9" is the largest palindromic integer that can be formed.
Note that the integer returned should not contain leading zeroes.
Constraints:
1 <= num.length <= 10^5numconsists of digits.
Solution
Approach: Greedy + Counting
Count each digit. For each digit d, count[d] / 2 pairs can be placed symmetrically around the center. Use at most one leftover digit as the center, and choose the largest digit that has an odd count.
Build the palindrome by wrapping the pairs around the center, going through the digits from small to large so the largest digits end up on the outside. Leading zeros make the number smaller, so strip the zeros from both ends; if nothing is left (only zeros were available), the answer is "0".
Complexity: time O(n), space O(n), where n is the length of num.
class Solution:
def largestPalindromic(self, num: str) -> str:
cnt = Counter(num)
ans = ''
for i in range(9, -1, -1):
v = str(i)
if cnt[v] % 2:
ans = v
cnt[v] -= 1
break
for i in range(10):
v = str(i)
if cnt[v]:
cnt[v] //= 2
s = cnt[v] * v
ans = s + ans + s
return ans.strip('0') or '0'