#2384
Largest Palindromic Number
MediumHash TableStringGreedyCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n!) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach counts the frequency of each digit and constructs the largest palindromic number by placing pairs of digits symmetrically around a potential center digit. This is efficient and avoids unnecessary permutations.
⚙️
Algorithm
4 steps- 1Step 1: Count the frequency of each digit in the string.
- 2Step 2: Construct the first half of the palindrome using pairs of digits, starting from the largest digit.
- 3Step 3: If any digit has an odd count, it can be used as the center of the palindrome.
- 4Step 4: Combine the first half, the center (if any), and the reverse of the first half to form the palindrome.
solution.py16 lines
1# Full working Python code
2from collections import Counter
3
4def largest_palindromic(num):
5 count = Counter(num)
6 first_half = []
7 center = ''
8 for digit in sorted(count.keys(), reverse=True):
9 pairs = count[digit] // 2
10 first_half.append(digit * pairs)
11 if count[digit] % 2 == 1 and center == '':
12 center = digit
13 first_half_str = ''.join(first_half)
14 if first_half_str == '' and center == '0':
15 return '0'
16 return first_half_str + center + first_half_str[::-1]ℹ
Complexity note: The time complexity is O(n) because we traverse the string once to count digits. The space complexity is O(1) since we only use a fixed-size array for digit counts.
- 1To form a palindrome, digits must be paired symmetrically.
- 2The largest digits should be prioritized to maximize the palindrome's value.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.