Largest Palindromic Number — LeetCode 2384 Python Solution

MediumGreedyHash TableStringCounting
Problem
#2384
Pattern
Greedy
Reading time
3 min

The 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.

Example

Input
num = "444947137"
Output
"7449447"
Explanation
Use the digits "4449477" from "444947137" to form the palindromic integer "7449447".

Python solution

Python
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'

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2384. Largest Palindromic Number is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2384. Largest Palindromic Number?
LeetCode 2384. Largest Palindromic Number is rated Medium on LeetCode.
What is the time complexity of LeetCode 2384. Largest Palindromic Number?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2384. Largest Palindromic Number?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2384. Largest Palindromic Number cover?
LeetCode 2384. Largest Palindromic Number is tagged Greedy, Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview