Given a number, find the next smallest palindrome

21 Jun, 2022
Given a number, find the next smallest palindrome larger than this number. For example, if the input number is “2 3 5 4 5”, the output should be “2 3 6 3 2”. And if the input number is “9 9 9”, the output should be “1 0 0 1”. The input is assumed to be an array. Every entry in array represents a digit in input number. Let the array be ‘num[]’ and size of array be ‘n’
There can be three different types of inputs that need to be handled separately. 1) The input number is palindrome and has all 9s. For example “9 9 9”. Output should be “1 0 0 1” 2) The input number is not palindrome. For example “1 2 3 4”. Output should be “1 3 3 1” 3) The input number is palindrome and doesn’t have all 9s. For example “1 2 2 1”. Output should be “1 3 3 1”.
Solution for input type 1 is easy. The output contains n + 1 digits where the corner digits are 1, and all digits between corner digits are 0.Now let us first talk about input type 2 and 3. How to convert a given number to a greater palindrome? To understand the solution, let us first define the following two terms: 
Left Side: The left half of given number. Left side of “1 2 3 4 5 6” is “1 2 3” and left side of “1 2 3 4 5” is “1 2” 
Right Side: The right half of given number. Right side of “1 2 3 4 5 6” is “4 5 6” and right side of “1 2 3 4 5” is “4 5” 
To convert to palindrome, we can either take the mirror of its left side or take mirror of its right side. However, if we take the mirror of the right side, then the palindrome so formed is not guaranteed to be next larger palindrome. So, we must take the mirror of left side and copy it to right side. But there are some cases that must be handled in different ways. See the following steps.We will start with two indices i and j. i pointing to the two middle elements (or pointing to two elements around the middle element in case of n being odd). We one by one move i and j away from each other.
Step 1. Initially, ignore the part of left side which is same as the corresponding part of right side. For example, if the number is “8 3 4 2 2 4 6 9′′, we ignore the middle four elements. i now points to element 3 and j now points to element 6.
Step 2. After step 1, following cases arise:Case 1: Indices i & j cross the boundary. This case occurs when the input number is palindrome. In this case, we just add 1 to the middle digit (or digits in case n is even) propagate the carry towards MSB digit of left side and simultaneously copy mirror of the left side to the right side. For example, if the given number is “1 2 9 2 1”, we increment 9 to 10 and propagate the carry. So the number becomes “1 3 0 3 1”
Case 2: There are digits left between left side and right side which are not same. So, we just mirror the left side to the right side & try to minimize the number formed to guarantee the next smallest palindrome. In this case, there can be two sub-cases. 
2.1) Copying the left side to the right side is sufficient, we don’t need to increment any digits and the result is just mirror of left side. Following are some examples of this sub-case. Next palindrome for “7 8 3 3 2 2′′ is “7 8 3 3 8 7” Next palindrome for “1 2 5 3 2 2′′ is “1 2 5 5 2 1” Next palindrome for “1 4 5 8 7 6 7 8 3 2 2′′ is “1 4 5 8 7 6 7 8 5 4 1” How do we check for this sub-case? All we need to check is the digit just after the ignored part in step 1. This digit is highlighted in above examples. If this digit is greater than the corresponding digit in right side digit, then copying the left side to the right side is sufficient and we don’t need to do anything else.
2.2) Copying the left side to the right side is NOT sufficient. This happens when the above defined digit of left side is smaller. Following are some examples of this case. Next palindrome for “7 1 3 3 2 2′′ is “7 1 4 4 1 7” Next palindrome for “1 2 3 4 6 2 8′′ is “1 2 3 5 3 2 1” Next palindrome for “9 4 1 8 7 9 7 8 3 2 2′′ is “9 4 1 8 8 0 8 8 1 4 9” We handle this subcase like Case 1. We just add 1 to the middle digit (or digits in case n is even) propagate the carry towards MSB digit of left side and simultaneously copy mirror of the left side to the right side.
Approach 1: Basic Approach for Finding the next smallest Palindrome Number.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;// Function to check whether number is palindrome or notint isPalindrome(int num){    // Declaring variables    int n, k, rev = 0;    // storing num in n so that we can compare it later    n = num;    // while num is not 0 we find its reverse and store in    // rev    while (num != 0) {        k = num % 10;        rev = (rev * 10) + k;        num = num / 10;    }    // check if num and its reverse are same    if (n == rev) {        return 1;    }    else {        return 0;    }}int main(){    // Take any number to find its next palindrome number    int num = 9687;    // If number is not Palindrome we go to the next number    // using while loop    while (!isPalindrome(num)) {        num = num + 1;    }    // now we get the next Palindrome so let's print it    cout << "Next Palindrome :";    cout << num;    return 0;}// Contribute by :- Tejas Bhavsar
import java.io.*; class GFG{       // Function to check whether number is palindrome or not    static int isPalindrome(int num)    {               // Declaring variables        int n, k, rev = 0;               // storing num in n so that we can compare it later        n = num;               // while num is not 0 we find its reverse and store        // in rev        while (num != 0) {            k = num % 10;            rev = (rev * 10) + k;            num = num / 10;        }               // check if num and its reverse are same        if (n == rev) {            return 1;        }        else {            return 0;        }    }     // Driver code    public static void main(String[] args)    {               // Take any number to find its next palindrome        // number        int num = 9687;               // If number is not Palindrome we go to the next        // number using while loop        while (isPalindrome(num) == 0) {            num = num + 1;        }               // now we get the next Palindrome so let's print it        System.out.print("Next Palindrome :");        System.out.print(num);    }} // This code is contributed by subhammahato348.
# Program to print find next palindrome# number greater than given number. # function to check a number is# palindrome or notdef isPalindrome(num):     # Declaring variables     # storing num in n so that we can compare it later    n = num    rev = 0     # while num is not 0 we find its reverse and store    # in rev    while (num > 0):        k = num % 10        rev = (rev * 10) + k        num = num // 10     # check if num and its reverse are same    if (n == rev):        return True    else:        return False  # input numbernum = 9687 # start check from next num;num = num + 1 # Loop checks all numbers from given no.# (num + 1) to next palindrome no.while (True):    if (isPalindrome(num)):        break    num = num + 1 # printing the next palindromeprint("Next Palindrome :")print(num) # This code is contributed by sidharthsingh7898.
using System;class GFG {     // Function to check whether number is palindrome or not    static int isPalindrome(int num)    {         // Declaring variables        int n, k, rev = 0;         // storing num in n so that we can compare it later        n = num;         // while num is not 0 we find its reverse and store        // in rev        while (num != 0) {            k = num % 10;            rev = (rev * 10) + k;            num = num / 10;        }         // check if num and its reverse are same        if (n == rev) {            return 1;        }        else {            return 0;        }    }     // Driver code    public static void Main()    {         // Take any number to find its next palindrome        // number        int num = 9687;         // If number is not Palindrome we go to the next        // number using while loop        while (isPalindrome(num) == 0) {            num = num + 1;        }         // now we get the next Palindrome so let's print it        Console.Write("Next Palindrome :");        Console.Write(num);    }} // This code is contributed by subhammahato348.
<script> // Javascript program for the above approach     // Function to check whether number is palindrome or not    function isPalindrome(num)    {               // Declaring variables        let n, k, rev = 0;               // storing num in n so that we can compare it later        n = num;               // while num is not 0 we find its reverse and store        // in rev        while (num != 0) {            k = num % 10;            rev = (rev * 10) + k;            num = Math.floor(num / 10);        }               // check if num and its reverse are same        if (n == rev) {            return 1;        }        else {            return 0;        }    } // Driver Code     // Take any number to find its next palindrome        // number        let num = 9687;               // If number is not Palindrome we go to the next        // number using while loop        while (isPalindrome(num) == 0) {            num = num + 1;        }               // now we get the next Palindrome so let's print it        document.write("Next Palindrome :");        document.write(num); // This code is contributed by splevel62.</script>
Next Palindrome :9779
Time Complexity: O(num * |num|)
Space Complexity: O(1)
C++
C
Java
Python3
C#
PHP
Javascript
#include <iostream>using namespace std; // Utility that prints out an array on a linevoid printArray(int arr[], int n){    int i;    for(i = 0; i < n; i++)        printf("%d ", arr[i]);             printf("\n");} // A utility function to check if num has all 9sint AreAll9s(int* num, int n ){    int i;    for(i = 0; i < n; ++i)        if (num[i] != 9)            return 0;                 return 1;} // Returns next palindrome of a given number num[].// This function is for input type 2 and 3void generateNextPalindromeUtil (int num[], int n ){         // Find the index of mid digit    int mid = n / 2;     // A bool variable to check if copy of left    // side to right is sufficient or not    bool leftsmaller = false;     // End of left side is always 'mid -1'    int i = mid - 1;     // Beginning of right side depends    // if n is odd or even    int j = (n % 2) ? mid + 1 : mid;    // Initially, ignore the middle same digits    while (i >= 0 && num[i] == num[j])        i--, j++;     // Find if the middle digit(s) need to be    // incremented or not (or copying left    // side is not sufficient)    if (i < 0 || num[i] < num[j])        leftsmaller = true;     // Copy the mirror of left to tight    while (i >= 0)    {        num[j] = num[i];        j++;        i--;    }     // Handle the case where middle digit(s) must    // be incremented. This part of code is for    // CASE 1 and CASE 2.2    if (leftsmaller == true)    {        int carry = 1;        i = mid - 1;         // If there are odd digits, then increment        // the middle digit and store the carry        if (n % 2 == 1)        {            num[mid] += carry;            carry = num[mid] / 10;            num[mid] %= 10;            j = mid + 1;        }        else            j = mid;         // Add 1 to the rightmost digit of the        // left side, propagate the carry towards        // MSB digit and simultaneously copying        // mirror of the left side to the right side.        while (i >= 0)        {            num[i] += carry;            carry = num[i] / 10;            num[i] %= 10;                         // Copy mirror to right            num[j++] = num[i--];        }    }} // The function that prints next palindrome// of a given number num[] with n digits.void generateNextPalindrome(int num[], int n){    int i;     printf("Next palindrome is:");     // Input type 1: All the digits are 9, simply o/p 1    // followed by n-1 0's followed by 1.    if (AreAll9s(num, n))    {        printf("1 ");        for(i = 1; i < n; i++)            printf("0 ");                     printf("1");    }     // Input type 2 and 3    else    {        generateNextPalindromeUtil(num, n);         // print the result        printArray (num, n);    }} // Driver codeint main(){    int num[] = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 };     int n = sizeof(num) / sizeof(num[0]);     generateNextPalindrome(num, n);     return 0;} // This code is contributed by rohan07
#include <stdio.h> // A utility function to print an arrayvoid printArray (int arr[], int n); // A utility function to check if num has all 9sint AreAll9s (int num[], int n ); // Returns next palindrome of a given number num[].// This function is for input type 2 and 3void generateNextPalindromeUtil (int num[], int n ){    // find the index of mid digit    int mid = n/2;     // A bool variable to check if copy of left side to right is sufficient or not    bool leftsmaller = false;     // end of left side is always 'mid -1'    int i = mid - 1;     // Beginning of right side depends if n is odd or even    int j = (n % 2)? mid + 1 : mid;    // Initially, ignore the middle same digits    while (i >= 0 && num[i] == num[j])        i--,j++;     // Find if the middle digit(s) need to be incremented or not (or copying left    // side is not sufficient)    if ( i < 0 || num[i] < num[j])        leftsmaller = true;     // Copy the mirror of left to tight    while (i >= 0)    {        num[j] = num[i];        j++;        i--;    }     // Handle the case where middle digit(s) must be incremented.    // This part of code is for CASE 1 and CASE 2.2    if (leftsmaller == true)    {        int carry = 1;        i = mid - 1;         // If there are odd digits, then increment        // the middle digit and store the carry        if (n%2 == 1)        {            num[mid] += carry;            carry = num[mid] / 10;            num[mid] %= 10;            j = mid + 1;        }        else            j = mid;         // Add 1 to the rightmost digit of the left side, propagate the carry        // towards MSB digit and simultaneously copying mirror of the left side        // to the right side.        while (i >= 0)        {            num[i] += carry;            carry = num[i] / 10;            num[i] %= 10;            num[j++] = num[i--]; // copy mirror to right        }    }} // The function that prints next palindrome of a given number num[]// with n digits.void generateNextPalindrome( int num[], int n ){    int i;     printf("Next palindrome is:");     // Input type 1: All the digits are 9, simply o/p 1    // followed by n-1 0's followed by 1.    if( AreAll9s( num, n ) )    {        printf( "1 ");        for( i = 1; i < n; i++ )            printf( "0 " );        printf( "1" );    }     // Input type 2 and 3    else    {        generateNextPalindromeUtil ( num, n );         // print the result        printArray (num, n);    }} // A utility function to check if num has all 9sint AreAll9s( int* num, int n ){    int i;    for( i = 0; i < n; ++i )        if( num[i] != 9 )            return 0;    return 1;} /* Utility that prints out an array on a line */void printArray(int arr[], int n){    int i;    for (i=0; i < n; i++)        printf("%d ", arr[i]);    printf("\n");} // Driver Program to test above functionint main(){    int num[] = {9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2};     int n = sizeof (num)/ sizeof(num[0]);     generateNextPalindrome( num, n );     return 0;}
// Java program to find next smallest// palindrome public class nextplaindrome{    // Returns next palindrome of a given    // number num[]. This function is for    // input type 2 and 3    static void generateNextPalindromeUtil(int num[], int n)    {        int mid = n / 2;         // end of left side is always 'mid -1'        int i = mid - 1;                 // Beginning of right side depends        // if n is odd or even        int j = (n % 2 == 0) ? mid : mid + 1;                 // A bool variable to check if copy of left        // side to right        // is sufficient or not        boolean leftsmaller = false;         // Initially, ignore the middle same digits        while (i >= 0 && num[i] == num[j])        {            i--;            j++;        }                 // Find if the middle digit(s) need to        // be incremented or not (or copying left        // side is not sufficient)        if (i < 0 || num[i] < num[j])        {            leftsmaller = true;        }                 // Copy the mirror of left to tight        while (i >= 0)        {            num[j++] = num[i--];        }                 // Handle the case where middle digit(s)        // must be incremented. This part of code        // is for CASE 1 and CASE 2.2        if (leftsmaller)        {            int carry = 1;                     // If there are odd digits, then increment            // the middle digit and store the carry            if (n % 2 == 1) {                num[mid] += 1;                carry = num[mid] / 10;                num[mid] %= 10;            }            i = mid - 1;            j = (n % 2 == 0 ? mid : mid + 1);                         // Add 1 to the rightmost digit of the left            // side, propagate the carry towards MSB digit            // and simultaneously copying mirror of the            // left side to the right side.            //when carry is zero no need to loop through till i>=0            while (i >= 0 && carry>0)             {                num[i] = num[i] + carry;                carry = num[i] / 10;                num[i] %= 10;                num[j] = num[i];// copy mirror to right                i--;                j++;            }         }    }     // The function that prints next palindrome    // of a given number num[] with n digits.    static void generateNextPalindrome(int num[], int n)    {        System.out.println("Next Palindrome is:");                 // Input type 1: All the digits are 9,        // simply o/p 1 followed by n-1 0's        // followed by 1.        if (isAll9(num, n)) {            System.out.print("1");            for (int i = 0; i < n - 1; i++)                System.out.print("0");            System.out.println("1");         }             // Input type 2 and 3        else {            generateNextPalindromeUtil(num, n);            printarray(num);        }    }     // A utility function to check if num has all 9s    static boolean isAll9(int num[], int n) {        for (int i = 0; i < n; i++)            if (num[i] != 9)                return false;        return true;    }     /* Utility that prints out an array on a line */    static void printarray(int num[]) {        for (int i = 0; i < num.length; i++)            System.out.print(num[i]);        System.out.println();    }     public static void main(String[] args)    {        int num[] = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 };        generateNextPalindrome(num, num.length);    }}
# Returns next palindrome of a given number num[].# This function is for input type 2 and 3def generateNextPalindromeUtil (num, n) :     # find the index of mid digit    mid = int(n/2 )     # A bool variable to check if copy of left    # side to right is sufficient or not    leftsmaller = False     # end of left side is always 'mid -1'    i = mid - 1     # Beginning of right side depends    # if n is odd or even    j = mid + 1 if (n % 2) else mid     # Initially, ignore the middle same digits    while (i >= 0 and num[i] == num[j]) :        i-=1        j+=1     # Find if the middle digit(s) need to be    # incremented or not (or copying left    # side is not sufficient)    if ( i < 0 or num[i] < num[j]):        leftsmaller = True     # Copy the mirror of left to tight    while (i >= 0) :             num[j] = num[i]        j+=1        i-=1          # Handle the case where middle    # digit(s) must be incremented.    # This part of code is for CASE 1 and CASE 2.2    if (leftsmaller == True) :             carry = 1        i = mid - 1         # If there are odd digits, then increment        # the middle digit and store the carry        if (n%2 == 1) :                     num[mid] += carry            carry = int(num[mid] / 10 )            num[mid] %= 10            j = mid + 1                 else:            j = mid         # Add 1 to the rightmost digit of the        # left side, propagate the carry        # towards MSB digit and simultaneously        # copying mirror of the left side        # to the right side.        while (i >= 0) :                     num[i] += carry            carry = int(num[i] / 10)            num[i] %= 10            num[j] = num[i] # copy mirror to right            j+=1            i-=1         # The function that prints next# palindrome of a given number num[]# with n digits.def generateNextPalindrome(num, n ) :     print("\nNext palindrome is:")     # Input type 1: All the digits are 9, simply o/p 1    # followed by n-1 0's followed by 1.    if( AreAll9s( num, n ) == True) :             print( "1")        for i in range(1, n):            print( "0" )        print( "1")          # Input type 2 and 3    else:             generateNextPalindromeUtil ( num, n )         # print the result        printArray (num, n)     # A utility function to check if num has all 9sdef AreAll9s(num, n ):    for i in range(1, n):        if( num[i] != 9 ) :            return 0    return 1  # Utility that prints out an array on a linedef printArray(arr, n):     for i in range(0, n):        print(int(arr[i]),end=" ")    print()  # Driver Program to test above functionif __name__ == "__main__":    num = [9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2]    n = len(num)    generateNextPalindrome( num, n ) # This code is contributed by Smitha Dinesh Semwal
// C# program to find next smallest  palindromeusing System;public class GFG {         // Returns next palindrome of a given    // number num[]. This function is for    // input type 2 and 3    static void generateNextPalindromeUtil(int []num, int n)    {        int mid = n / 2;         // end of left side is always 'mid -1'        int i = mid - 1;                 // Beginning of right side depends        // if n is odd or even        int j = (n % 2 == 0) ? mid : mid + 1;                 // A bool variable to check if copy of left        // side to right        // is sufficient or not        bool leftsmaller = false;         // Initially, ignore the middle same digits        while (i >= 0 && num[i] == num[j])        {            i--;            j++;        }                 // Find if the middle digit(s) need to        // be incremented or not (or copying left        // side is not sufficient)        if (i < 0 || num[i] < num[j])        {            leftsmaller = true;        }                 // Copy the mirror of left to tight        while (i >= 0)        {            num[j++] = num[i--];        }                 // Handle the case where middle digit(s)        // must be incremented. This part of code        // is for CASE 1 and CASE 2.2        if (leftsmaller)        {            int carry = 1;                     // If there are odd digits, then increment            // the middle digit and store the carry            if (n % 2 == 1) {                num[mid] += 1;                carry = num[mid] / 10;                num[mid] %= 10;            }            i = mid - 1;            j = (n % 2 == 0 ? mid : mid + 1);                         // Add 1 to the rightmost digit of the left            // side, propagate the carry towards MSB digit            // and simultaneously copying mirror of the            // left side to the right side.            while (i >= 0)            {                num[i] = num[i] + carry;                carry = num[i] / 10;                num[i] %= 10;                num[j] = num[i];// copy mirror to right                i--;                j++;            }         }    }     // The function that prints next palindrome    // of a given number num[] with n digits.    static void generateNextPalindrome(int []num, int n)    {        Console.WriteLine("Next Palindrome is:");                 // Input type 1: All the digits are 9,        // simply o/p 1 followed by n-1 0's        // followed by 1.        if (isAll9(num, n)) {            Console.Write("1");            for (int i = 0; i < n - 1; i++)                Console.Write("0");            Console.Write("1");         }             // Input type 2 and 3        else {            generateNextPalindromeUtil(num, n);            printarray(num);        }    }     // A utility function to check if num has all 9s    static bool isAll9(int[] num, int n) {        for (int i = 0; i < n; i++)            if (num[i] != 9)                return false;        return true;    }     /* Utility that prints out an array on a line */    static void printarray(int []num) {        for (int i = 0; i < num.Length; i++)            Console.Write(num[i]+ " ");        Console.Write(" ");    }     // Driver code    public static void Main()    {        int []num = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 };        generateNextPalindrome(num, num.Length);    }} // This code is contributed by Smitha.
<?php// PHP program to find next// smallest palindrome // Returns next palindrome// of a given number num[].// This function is for// input type 2 and 3function generateNextPalindromeUtil($num, $n){    $mid = (int)($n / 2);     // end of left side    // is always 'mid -1'    $i = $mid - 1;         // Beginning of right    // side depends if n    // is odd or even    $j = ($n % 2 == 0) ?                  $mid : ($mid + 1);         // A bool variable to check    // if copy of left side to    // right is sufficient or not    $leftsmaller = false;     // Initially, ignore the    // middle same digits    while ($i >= 0 &&           $num[$i] == $num[$j])    {        $i--;        $j++;    }         // Find if the middle digit(s)    // need to be incremented or    // not (or copying left side    // is not sufficient)    if ($i < 0 || $num[$i] < $num[$j])    {        $leftsmaller = true;    }         // Copy the mirror    // of left to tight    while ($i >= 0)    {        $num[$j++] = $num[$i--];    }         // Handle the case where    // middle digit(s) must be    // incremented. This part    // of code is for CASE 1    // and CASE 2.2    if ($leftsmaller)    {        $carry = 1;             // If there are odd digits,        // then increment the middle        // digit and store the carry        if ($n % 2 == 1)        {            $num[$mid] += 1;            $carry = (int)($num[$mid] / 10);            $num[$mid] %= 10;        }        $i = $mid - 1;        $j = ($n % 2 == 0 ?                     $mid : $mid + 1);                 // Add 1 to the rightmost digit        // of the left side, propagate        // the carry towards MSB digit        // and simultaneously copying        // mirror of the left side to        // the right side.        while ($i >= 0)        {            $num[$i] = $num[$i] + $carry;            $carry = (int)($num[$i] / 10);            $num[$i] %= 10;                         // copy mirror to right            $num[$j] = $num[$i];            $i--;            $j++;        }     }return $num;} // The function that prints// next palindrome of a given// number num[] with n digits.function generateNextPalindrome($num, $n){    echo "Next Palindrome is:\n";         // Input type 1: All the    // digits are 9, simply    // o/p 1 followed by n-1    // 0's followed by 1.    if (isAll9($num, $n))    {        echo "1";        for ($i = 0; $i < $n - 1; $i++)            echo "0";        echo "1";     }     // Input type 2 and 3    else    {        $num = generateNextPalindromeUtil($num, $n);            printarray($num);    }} // A utility function to// check if num has all 9sfunction isAll9($num, $n){    for ($i = 0; $i < $n; $i++)        if ($num[$i] != 9)            return false;    return true;} /* Utility that prints outan array on a line */function printarray($num){    for ($i = 0;         $i < count($num); $i++)        echo $num[$i];    echo "\n";} // Driver code$num = array(9, 4, 1, 8, 7,             9, 7, 8, 3, 2, 2);generateNextPalindrome($num,               count($num)); // This code is contributed by mits.?>
<script> // JavaScript program to find next smallest// palindrome  // Returns next palindrome of a given// number num. This function is for// input type 2 and 3function generateNextPalindromeUtil(num , n){    var mid = parseInt(n / 2);     // end of left side is always 'mid -1'    var i = mid - 1;         // Beginning of right side depends    // if n is odd or even    var j = (n % 2 == 0) ? mid : mid + 1;         // A bool variable to check if copy of left    // side to right    // is sufficient or not    leftsmaller = false;     // Initially, ignore the middle same digits    while (i >= 0 && num[i] == num[j])    {        i--;        j++;    }         // Find if the middle digit(s) need to    // be incremented or not (or copying left    // side is not sufficient)    if (i < 0 || num[i] < num[j])    {        leftsmaller = true;    }         // Copy the mirror of left to tight    while (i >= 0)    {        num[j++] = num[i--];    }         // Handle the case where middle digit(s)    // must be incremented. This part of code    // is for CASE 1 and CASE 2.2    if (leftsmaller)    {        var carry = 1;             // If there are odd digits, then increment        // the middle digit and store the carry        if (n % 2 == 1) {            num[mid] += 1;            carry = parseInt(num[mid] / 10);            num[mid] %= 10;        }        i = mid - 1;        j = (n % 2 == 0 ? mid : mid + 1);                 // Add 1 to the rightmost digit of the left        // side, propagate the carry towards MSB digit        // and simultaneously copying mirror of the        // left side to the right side.        //when carry is zero no need to loop through till i>=0        while (i >= 0 && carry>0)         {            num[i] = num[i] + carry;            carry = parseInt(num[i] / 10);            num[i] %= 10;            num[j] = num[i];// copy mirror to right            i--;            j++;        }     }} // The function that prints next palindrome// of a given number num with n digits.function generateNextPalindrome(num , n){    document.write("Next Palindrome is: <br>");         // Input type 1: All the digits are 9,    // simply o/p 1 followed by n-1 0's    // followed by 1.    if (isAll9(num, n)) {        document.write("1");        for (i = 0; i < n - 1; i++)            document.write("0");        document.write("1");     }     // Input type 2 and 3    else {        generateNextPalindromeUtil(num, n);        printarray(num);    }} // A utility function to check if num has all 9sfunction isAll9(num , n) {    for (i = 0; i < n; i++)        if (num[i] != 9)            return false;    return true;} /* Utility that prints out an array on a line */function printarray(num) {    for (i = 0; i < num.length; i++)        document.write(num[i]+"\n");}   var num = [ 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 ];generateNextPalindrome(num, num.length); // This code is contributed by 29AjayKumar </script>
Next palindrome is:9 4 1 8 8 0 8 8 1 4 9 
Time Complexity: O(num)
Space Complexity: O(1)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Smitha Dinesh Semwal
Mithun Kumar
hritikgupta
ankush_953
Akanksha_Rai
rohit768
ashraf61242
29AjayKumar
rohan07
tejasbhavsar06
subhammahato348
siddharthsingh7898
rishavmahato348
surindertarika1234
splevel62
amartyaghoshgfg
khushboogoyal499
geekygirl2001
Amazon
FactSet
MakeMyTrip
Microsoft
palindrome
Prime Number
Yahoo
Arrays
Mathematical
Sorting
Strings
Amazon
Microsoft
FactSet
MakeMyTrip
Yahoo
Arrays
Strings
Mathematical
Sorting
Prime Number
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays