VOOZH about

URL: https://www.geeksforgeeks.org/dsa/next-higher-palindromic-number-using-set-digits/

⇱ Next higher palindromic number using the same set of digits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Next higher palindromic number using the same set of digits

Last Updated : 24 May, 2026

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.

[Brute Force Approach] Checking Every Larger Number – O(10ⁿ × n) Time and O(1) Space

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, -1 is returned.


Output
Input: 1221
Output: 2112

[Efficient Approach] Using Next Permutation Logic on First Half – O(n) Time and O(1) Space

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.

  • Find the middle index of the palindrome
  • Traverse the first half from right to left: Find the first decreasing digit
  • If no such digit exists, return -1
  • Find the smallest greater digit on the right side
  • Swap both corresponding palindrome positions
  • Reverse the remaining portions of both halves and return the resulting palindrome

Output
Input: 4697557964
Output: 4756996574
Comment