Open In App

Next higher palindromic number using the same set of digits

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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 print “Not Possible”. 
The number could be very large and may or may not even fit into long long int.

Examples: 

Input : 4697557964
Output :  4756996574

Input : 543212345
Output : Not Possible

Approach:  

Follow the below steps to solve the problem:

  1. If number of digits n <= 3, then print “Not Possible” and return.
  2. Calculate mid = n/2 – 1.
  3. Start traversing from the digit at index mid up to the 1st digit and while traversing find the index i of the rightmost digit which is smaller than the digit on its right side.
  4. Now search for the smallest digit greater than the digit num[i] in the index range i+1 to mid. Let the index of this digit be smallest.
  5. If no such smallest digit found, then print “Not Possible”.
  6. Else the swap the digits at index i and smallest and also swap the digits at index n-i-1 and n-smallest-1. This step is done so as to maintain the palindromic property in num.
  7. Now reverse the digits in the index range i+1 to mid. Also If n is even then reverse the digits in the index range mid+1 to n-i-2 else if n is odd then reverse the digits in the index range mid+2 to n-i-2. This step is done so as to maintain the palindromic property in num.
  8. Print the final modified number num.

Implementation:

C





C++





Java





Python





C#





PHP





Javascript





Output

Next Palindrome: 4756996574

Time Complexity: O(n)
Auxiliary Space: O(1)



Last Updated : 26 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads