![]() |
VOOZH | about |
Given a palindromic number num having n number of digits. The problem is to find the smallest palindromic number greater than num using the same set of digits as in num. If no such number can be formed then return "-1".
Examples:
Input: n = "35453"
Output: 53435
Explanation: Next higher palindromic number is 53435.Input: n = "33"
Output: -1
Explanation: Next higher palindromic number does not exist.
Table of Content
The idea is to generate every number greater than the given palindrome and check whether it satisfies two conditions:
- It must itself be a palindrome
- It must contain the same frequency of digits as the original number
For every candidate number, palindrome verification is performed using two pointers, and digit frequencies are compared using frequency arrays. The first valid number found is returned as the next palindrome. If no such number exists,
-1is returned.
Input: 1221 Output: 2112
The idea is based on the observation that a palindrome is completely determined by its first half. To obtain the next greater palindromic number using the same digits, we generate the next lexicographically greater arrangement of the first half of the palindrome and mirror the changes in the second half. If the first half is already in descending order, then no larger palindrome can be formed using the same digits.
-1Input: 4697557964 Output: 4756996574