Leetcode 2384: Largest Palindromic Number

grid47
grid47
Exploring patterns and algorithms
Mar 13, 2024 6 min read

You are given a string num consisting only of digits. Your task is to form the largest possible palindromic number by rearranging the digits of num. The resulting number should not have leading zeros and must use at least one digit from the string.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `num` of length `n` containing only digits.
Example: Input: num = '123321'
Constraints:
• 1 <= num.length <= 10^5
• num consists of digits only.
Output: Return the largest palindromic number that can be formed from the digits of `num`. The result should be a string.
Example: Output: '321123'
Constraints:
Goal: To form the largest possible palindromic number from the digits, rearrange them to maximize the digits in the left half and mirror them on the right side.
Steps:
• 1. Count the occurrences of each digit in the string.
• 2. Build the first half of the palindrome by placing as many pairs of digits as possible in descending order.
• 3. If there is any digit with an odd count, place it in the center of the palindrome.
• 4. Mirror the first half to create the full palindrome.
Goal: Ensure that the solution handles input sizes up to 100,000 digits efficiently and avoids leading zeros in the resulting palindrome.
Steps:
• Input string `num` will contain only digits and can have up to 100,000 characters.
Assumptions:
• The input will always contain at least one non-zero digit.
Input: Input: num = '123321'
Explanation: In this example, we can rearrange the digits to form '321123', which is the largest palindromic number. The digits are arranged so that the first half is mirrored to the second half.

Input: Input: num = '00009'
Explanation: In this case, the only non-zero digit is '9', so the largest palindromic number we can form is simply '9'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus