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

18 May, 2021
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: Following are the steps:
If number of digits n <= 3, then print “Not Possible” and return.Calculate mid = n/2 – 1.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.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.If no such smallest digit found, then print “Not Possible”.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.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.Print the final modified number num.
If number of digits n <= 3, then print “Not Possible” and return.
Calculate mid = n/2 – 1.
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.
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.
If no such smallest digit found, then print “Not Possible”.
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.
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.
Print the final modified number num.
C++
Java
Python
C#
PHP
Javascript
// C++ implementation to find next higher// palindromic number using the same set// of digits#include <bits/stdc++.h>using namespace std; // function to reverse the digits in the// range i to j in 'num'void reverse(char num[], int i, int j){    while (i < j) {        swap(num[i], num[j]);        i++;        j--;    }} // function to find next higher palindromic// number using the same set of digitsvoid nextPalin(char num[], int n){    // if length of number is less than '3'    // then no higher palindromic number    // can be formed    if (n <= 3) {        cout << "Not Possible";        return;    }     // find the index of last digit    // in the 1st half of 'num'    int mid = n / 2 - 1;    int i, j;     // Start from the (mid-1)th digit and    // find the first digit that is    // smaller than the digit next to it.    for (i = mid - 1; i >= 0; i--)        if (num[i] < num[i + 1])            break;     // If no such digit is found, then all    // digits are in descending order which    // means there cannot be a greater    // palindromic number with same set of    // digits    if (i < 0) {        cout << "Not Possible";        return;    }     // Find the smallest digit on right    // side of ith digit which is greater    // than num[i] up to index 'mid'    int smallest = i + 1;    for (j = i + 2; j <= mid; j++)        if (num[j] > num[i] &&            num[j] <= num[smallest])            smallest = j;     // swap num[i] with num[smallest]    swap(num[i], num[smallest]);     // as the number is a palindrome, the same    // swap of digits should be performed in    // the 2nd half of 'num'    swap(num[n - i - 1], num[n - smallest - 1]);     // reverse digits in the range (i+1) to mid    reverse(num, i + 1, mid);     // if n is even, then reverse digits in the    // range mid+1 to n-i-2    if (n % 2 == 0)        reverse(num, mid + 1, n - i - 2);     // else if n is odd, then reverse digits    // in the range mid+2 to n-i-2    else        reverse(num, mid + 2, n - i - 2);     // required next higher palindromic number    cout << "Next Palindrome: "         << num;} // Driver program to test aboveint main(){    char num[] = "4697557964";    int n = strlen(num);    nextPalin(num, n);    return 0;}
// Java implementation to find next higher// palindromic number using the same set// of digitsimport java.util.*; class NextHigherPalindrome{    // function to reverse the digits in the    // range i to j in 'num'    public static void reverse(char num[], int i,                                          int j)    {        while (i < j) {            char temp = num[i];            num[i] = num[j];            num[j] = temp;            i++;            j--;        }    }         // function to find next higher palindromic    // number using the same set of digits    public static void nextPalin(char num[], int n)    {        // if length of number is less than '3'        // then no higher palindromic number        // can be formed        if (n <= 3) {            System.out.println("Not Possible");            return;        }        char temp;                 // find the index of last digit        // in the 1st half of 'num'        int mid = n / 2 - 1;        int i, j;             // Start from the (mid-1)th digit and        // find the first digit that is        // smaller than the digit next to it.        for (i = mid - 1; i >= 0; i--)            if (num[i] < num[i + 1])                break;             // If no such digit is found, then all        // digits are in descending order which        // means there cannot be a greater        // palindromic number with same set of        // digits        if (i < 0) {            System.out.println("Not Possible");            return;        }             // Find the smallest digit on right        // side of ith digit which is greater        // than num[i] up to index 'mid'        int smallest = i + 1;        for (j = i + 2; j <= mid; j++)            if (num[j] > num[i] &&                num[j] <= num[smallest])                smallest = j;             // swap num[i] with num[smallest]        temp = num[i];        num[i] = num[smallest];        num[smallest] = temp;                 // as the number is a palindrome,        // the same swap of digits should        // be performed in the 2nd half of        // 'num'        temp = num[n - i - 1];        num[n - i - 1] = num[n - smallest - 1];        num[n - smallest - 1] = temp;                 // reverse digits in the range (i+1)        // to mid        reverse(num, i + 1, mid);             // if n is even, then reverse        // digits in the range mid+1 to        // n-i-2        if (n % 2 == 0)            reverse(num, mid + 1, n - i - 2);             // else if n is odd, then reverse        // digits in the range mid+2 to n-i-2        else            reverse(num, mid + 2, n - i - 2);             // required next higher palindromic        // number        String result=String.valueOf(num);        System.out.println("Next Palindrome: "+                                   result);    }         // Driver Code    public static void main(String args[])    {        String str="4697557964";        char num[]=str.toCharArray();        int n=str.length();        nextPalin(num,n);    }} // This code is contributed by Danish Kaleem
# Python implementation to find next higher# palindromic number using the same set# of digits # function to reverse the digits in the# range i to j in 'num'def reverse(num, i, j) :         while (i < j) :        temp = num[i]        num[i] = num[j]        num[j] = temp        i = i + 1        j = j - 1              # function to find next higher palindromic# number using the same set of digitsdef nextPalin(num, n) :         # if length of number is less than '3'    # then no higher palindromic number    # can be formed    if (n <= 3) :        print "Not Possible"        return         # find the index of last digit    # in the 1st half of 'num'    mid = n / 2 - 1         # Start from the (mid-1)th digit and    # find the first digit that is    # smaller than the digit next to it.    i = mid - 1    while i >= 0 :        if (num[i] < num[i + 1]) :            break        i = i - 1         # If no such digit is found, then all    # digits are in descending order which    # means there cannot be a greater    # palindromic number with same set of    # digits    if (i < 0) :        print "Not Possible"        return         # Find the smallest digit on right    # side of ith digit which is greater    # than num[i] up to index 'mid'    smallest = i + 1    j = i + 2    while j <= mid :        if (num[j] > num[i] and num[j] <                        num[smallest]) :            smallest = j        j = j + 1         # swap num[i] with num[smallest]    temp = num[i]    num[i] = num[smallest]    num[smallest] = temp         # as the number is a palindrome,    # the same swap of digits should    # be performed in the 2nd half of    # 'num'    temp = num[n - i - 1]    num[n - i - 1] = num[n - smallest - 1]    num[n - smallest - 1] = temp         # reverse digits in the range (i+1)    # to mid    reverse(num, i + 1, mid)         # if n is even, then reverse    # digits in the range mid+1 to    # n-i-2    if (n % 2 == 0) :        reverse(num, mid + 1, n - i - 2)             # else if n is odd, then reverse    # digits in the range mid+2 to n-i-2    else :        reverse(num, mid + 2, n - i - 2)                      # required next higher palindromic    # number    result = ''.join(num)         print "Next Palindrome: ",result     # Driver Codest = "4697557964"num = list(st)n = len(st)nextPalin(num, n) # This code is contributed by Nikita Tiwari
// C# implementation to find// next higher palindromic// number using the same set// of digitsusing System; class GFG{    // function to reverse    // the digits in the    // range i to j in 'num'    public static void reverse(char[] num,                               int i, int j)    {        while (i < j)        {            char temp = num[i];            num[i] = num[j];            num[j] = temp;            i++;            j--;        }    }         // function to find next    // higher palindromic number    // using the same set of digits    public static void nextPalin(char[] num,                                 int n)    {        // if length of number is        // less than '3' then no        // higher palindromic number        // can be formed        if (n <= 3)        {            Console.WriteLine("Not Possible");            return;        }        char temp;                 // find the index of last        // digit in the 1st half        // of 'num'        int mid = n / 2 - 1;        int i, j;             // Start from the (mid-1)th        // digit and find the        // first digit that is        // smaller than the digit        // next to it.        for (i = mid - 1; i >= 0; i--)            if (num[i] < num[i + 1])                break;             // If no such digit is found,        // then all digits are in        // descending order which        // means there cannot be a        // greater palindromic number        // with same set of digits        if (i < 0)        {            Console.WriteLine("Not Possible");            return;        }             // Find the smallest digit on        // right side of ith digit         // which is greater than num[i]        // up to index 'mid'        int smallest = i + 1;        for (j = i + 2; j <= mid; j++)            if (num[j] > num[i] &&                num[j] < num[smallest])                smallest = j;             // swap num[i] with        // num[smallest]        temp = num[i];        num[i] = num[smallest];        num[smallest] = temp;                 // as the number is a palindrome,        // the same swap of digits should        // be performed in the 2nd half of        // 'num'        temp = num[n - i - 1];        num[n - i - 1] = num[n - smallest - 1];        num[n - smallest - 1] = temp;                 // reverse digits in the         // range (i+1) to mid        reverse(num, i + 1, mid);             // if n is even, then        // reverse digits in the        // range mid+1 to n-i-2        if (n % 2 == 0)            reverse(num, mid + 1,                    n - i - 2);             // else if n is odd, then        // reverse digits in the        // range mid+2 to n-i-2        else            reverse(num, mid + 2,                    n - i - 2);             // required next higher        // palindromic number        String result = new String(num);        Console.WriteLine("Next Palindrome: "+                                      result);    }         // Driver Code    public static void Main()    {        String str = "4697557964";        char[] num = str.ToCharArray();        int n = str.Length;        nextPalin(num, n);    }} // This code is contributed by mits
<?php// PHP implementation to find// next higher palindromic number// using the same set of digits // function to reverse the digits// in the range i to j in 'num'function reverse(&$num, $i, $j){    while ($i < $j)    {        $t = $num[$i];        $num[$i] = $num[$j];        $num[$j] = $t;        $i++;        $j--;    }} // function to find next higher// palindromic number using the// same set of digitsfunction nextPalin($num, $n){    // if length of number is less    // than '3' then no higher    // palindromic number can be formed    if ($n <= 3)    {        echo "Not Possible";        return;    }     // find the index of last digit    // in the 1st half of 'num'    $mid = ($n / 2) - 1;    $i = $mid - 1;    $j;     // Start from the (mid-1)th digit    // and find the first digit    // that is smaller than the digit    // next to it.    for (; $i >= 0; $i--)        if ($num[$i] < $num[$i + 1])            break;     // If no such digit is found,    // then all digits are in    // descending order which means    // there cannot be a greater    // palindromic number with same    // set of digits    if ($i < 0)    {        echo "Not Possible";        return;    }     // Find the smallest digit on right    // side of ith digit which is greater    // than num[i] up to index 'mid'    $smallest = $i + 1;    $j = 0;    for ($j = $i + 2; $j <= $mid; $j++)        if ($num[$j] > $num[$i] &&            $num[$j] < $num[$smallest])            $smallest = $j;     // swap num[i] with num[smallest]    $t = $num[$i];    $num[$i] = $num[$smallest];    $num[$smallest] = $t;         // as the number is a palindrome,    // the same swap of digits should    // be performed in the 2nd half of 'num'    $t = $num[$n - $i - 1];    $num[$n - $i - 1] = $num[$n - $smallest - 1];    $num[$n - $smallest - 1] = $t;     // reverse digits in the    // range (i+1) to mid    reverse($num, $i + 1, $mid);     // if n is even, then    // reverse digits in the    // range mid+1 to n-i-2    if ($n % 2 == 0)        reverse($num, $mid + 1, $n - $i - 2);     // else if n is odd, then reverse    // digits in the range mid+2    // to n-i-2    else        reverse($num, $mid + 2, $n - $i - 2);     // required next higher    // palindromic number    echo "Next Palindrome: " . $num;} // Driver Code$num = "4697557964";$n = strlen($num);nextPalin($num, $n); // This code is contributed by mits?>
<script> // Javascript implementation to find next higher// palindromic number using the same set// of digitsclass NextHigherPalindrome // Function to reverse the digits in the// range i to j in 'num'function reverse(num , i, j){    while (i < j)    {        var temp = num[i];        num[i] = num[j];        num[j] = temp;        i++;        j--;    }} // Function to find next higher palindromic// number using the same set of digitsfunction nextPalin(num, n){         // If length of number is less than '3'    // then no higher palindromic number    // can be formed    if (n <= 3)    {        document.write("Not Possible");        return;    }    var temp;         // Find the index of last digit    // in the 1st half of 'num'    var mid = n / 2 - 1;    var i, j;     // Start from the (mid-1)th digit and    // find the first digit that is    // smaller than the digit next to it.    for(i = mid - 1; i >= 0; i--)        if (num[i] < num[i + 1])            break;     // If no such digit is found, then all    // digits are in descending order which    // means there cannot be a greater    // palindromic number with same set of    // digits    if (i < 0)    {        document.write("Not Possible");        return;    }     // Find the smallest digit on right    // side of ith digit which is greater    // than num[i] up to index 'mid'    var smallest = i + 1;    for(j = i + 2; j <= mid; j++)        if (num[j] > num[i] &&            num[j] <= num[smallest])            smallest = j;     // Swap num[i] with num[smallest]    temp = num[i];    num[i] = num[smallest];    num[smallest] = temp;         // As the number is a palindrome,    // the same swap of digits should    // be performed in the 2nd half of    // 'num'    temp = num[n - i - 1];    num[n - i - 1] = num[n - smallest - 1];    num[n - smallest - 1] = temp;         // Reverse digits in the range (i+1)    // to mid    reverse(num, i + 1, mid);     // If n is even, then reverse    // digits in the range mid+1 to    // n-i-2    if (n % 2 == 0)        reverse(num, mid + 1, n - i - 2);     // Else if n is odd, then reverse    // digits in the range mid+2 to n-i-2    else        reverse(num, mid + 2, n - i - 2);     // Required next higher palindromic    // number    var result = num.join('');    document.write("Next Palindrome: "+                   result);} // Driver Codevar str = "4697557964";var num = str.split('');var n = str.length; nextPalin(num,n); // This code is contributed by 29AjayKumar </script>
Output: 
Next Palindrome: 4756996574
Time Complexity: O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Mithun Kumar
Akanksha_Rai
shivam2608
29AjayKumar
number-digits
Numbers
palindrome
Mathematical
Strings
Strings
Mathematical
Numbers
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Python program to check if a string is palindrome or not
Different methods to reverse a string in C/C++