Sei sulla pagina 1di 15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

GeeksforGeeks
A computer science portal for geeks

Placements

Practice

GATE CS

IDE

Q&A

GeeksQuiz
Login/Register

Given a number, nd the next smallest palindrome


Given a number, nd 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 doesnt have all 9s. For example 1 2 2 1. Output should be 1 3 3 1.

We strongly recommend that you click here and practice it, before moving on
to the solution.

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 rst talk about input type 2 and 3. How to convert a given number to a greater palindrome? To
understand the solution, let us rst dene 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:

http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

1/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

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 sufcient, we dont 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 sufcient and we dont need to do anything else.
2.2) Copying the left side to the right side is NOT sufcient. This happens when the above dened 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 ase n is even) propagate the carry
towards MSB digit of left side and simultaneously copy mirror of the left side to the right side.
#include<stdio.h>

//Autilityfunctiontoprintanarray
voidprintArray(intarr[],intn)

//Autilityfunctiontocheckifnumhasall9s
intAreAll9s(intnum[],intn)

//Returnsnextpalindromeofagivennumbernum[].
//Thisfunctionisforinputtype2and3
voidgenerateNextPalindromeUtil(intnum[],intn)
{
//findtheindexofmiddigit
intmid=n/2

//Aboolvariabletocheckifcopyofleftsidetorightissufficientornot
boolleftsmaller=false

//endofleftsideisalways'mid1'
inti=mid1

//Beginingofrightsidedependsifnisoddoreven
intj=(n%2)?mid+1:mid

//Initially,ignorethemiddlesamedigits
while(i>=0&&num[i]==num[j])
i,j++

//Findifthemiddledigit(s)needtobeincrementedornot(orcopyingleft
//sideisnotsufficient)
if(i<0||num[i]<num[j])
leftsmaller=true

//Copythemirroroflefttotight

http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

2/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

//Copythemirroroflefttotight
while(i>=0)
{
num[j]=num[i]
j++
i
}

//Handlethecasewheremiddledigit(s)mustbeincremented.
//ThispartofcodeisforCASE1andCASE2.2
if(leftsmaller==true)
{
intcarry=1
i=mid1

//Ifthereareodddigits,thenincrement
//themiddledigitandstorethecarry
if(n%2==1)
{
num[mid]+=carry
carry=num[mid]/10
num[mid]%=10
j=mid+1
}
else
j=mid

//Add1totherightmostdigitoftheleftside,propagatethecarry
//towardsMSBdigitandsimultaneouslycopyingmirroroftheleftside
//totherightside.
while(i>=0)
{
num[i]+=carry
carry=num[i]/10
num[i]%=10
num[j++]=num[i]//copymirrortoright
}
}
}

//Thefunctionthatprintsnextpalindromeofagivennumbernum[]
//withndigits.
voidgenerateNextPalindrome(intnum[],intn)
{
inti

printf("\nNextpalindromeis:\n")

//Inputtype1:Allthedigitsare9,simplyo/p1
//followedbyn10'sfollowedby1.
if(AreAll9s(num,n))
{
printf("1")
for(i=1i<ni++)
printf("0")
printf("1")
}

//Inputtype2and3
else
{
generateNextPalindromeUtil(num,n)

//printtheresult
printArray(num,n)
}
}

//Autilityfunctiontocheckifnumhasall9s
intAreAll9s(int*num,intn)
{
inti
for(i=0i<n++i)
if(num[i]!=9)
return0

http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

3/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

return0
return1
}

/*Utilitythatprintsoutanarrayonaline*/
voidprintArray(intarr[],intn)
{
inti
for(i=0i<ni++)
printf("%d",arr[i])
printf("\n")
}

//DriverProgramtotestabovefunction
intmain()
{
intnum[]={9,4,1,8,7,9,7,8,3,2,2}

intn=sizeof(num)/sizeof(num[0])

generateNextPalindrome(num,n)

return0
}
Run on IDE

Output:
Next palindrome is:
94188088149

Please write comments if you nd anything incorrect, or you want to share more information about the topic
discussed above.

Company Wise Coding Practice Topic Wise Coding Practice


56 Comments Category: Mathematical Tags: MathematicalAlgo

Related Posts:
Find the minimum value of m that satises ax + by = m and all values after m also satisfy
Finding number of digits in nth Fibonacci number
Carmichael Numbers
Multiples of 3 or 7
Count Divisors of Factorial
Non Fibonacci Numbers
Find Last Digit Of a^b for Large Numbers
Reverse and Add Function

http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

4/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

(Login to Rate and Mark)

Average Difculty : 4/5.0


Based on 35 vote(s)

Add to TODO List


Mark as DONE

Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the link here.

56 Comments
Recommend

GeeksforGeeks

Share

Login

Sort by Newest

Join the discussion


malik a month ago

checking for case like 999 etc can be avoided if we check in last if(carry>0) thn we have to
increase the size otherwise there is no need for it. Hope It helps :)

Reply Share
pranesh Kumar 2 months ago

http://code.geeksforgeeks.org/...

Reply Share
Ananyo Maiti > pranesh Kumar a month ago

Doesn't work for palindrome numbers like 999 and numbers like 713322 where left
side digit is smaller than right side.

Reply Share
pranesh Kumar 2 months ago

#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
int main()
{
char a[10];
cin>>a;
int length = strlen(a);
int orginal = atoi(a);
for(int i=0,j=length - 1;i<j;i++,j--) {="" a[j]="a[i];" }="" int="" palidrom="atoi(a);"
if(palidrom=""> orginal)
cout << palidrom << endl;
else
{
int j = 0,k = 1,ag = 1;
while(j < length/2)
{
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

5/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

see more

Reply Share
wilson 5 months ago

simple solution
https://ideone.com/QelC7L

Reply Share
Rahul Joshi > wilson 2 months ago

wrong answer for 849987 and for numbers with all 9s like '999999'.

Reply Share
Soham Chakravarty 7 months ago

A simpler solution. Code with comments: http://ideone.com/kOBmKa

Reply Share
Debashis Kumar Das 7 months ago

Please check this simple solution:


import java.io.BueredInputStream;
import java.util.Scanner;
public class Palindrome {
public static boolean isPalindrome(int num){
int temp = num;
int sum = 0;
while(num > 0){
sum = (sum * 10) + num % 10;
num = num / 10;
}
see more

Reply Share
atul 9 months ago

http://ideone.com/4mkGvT

Reply Share
Sahil a year ago

I have done it with a more simple and recursive approach. Check my solution
http://ideone.com/ZTB9ds

Reply Share
Shubham Aggarwal a year ago

http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

6/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

Shubham Aggarwal a year ago

Any suggestions guys whats wrong with this code ? grtting wrong ans
#include<stdio.h>
int palindrome(long int n)
{
long int t,rev=0;
t=n;
while(t)
{
rev=rev*10;
rev=rev+t%10;
t=t/10;
see more

Reply Share
Dman a year ago

Easy C++ implementation


https://ideone.com/NFwyMd

Reply Share
deeksha garg a year ago

plzz can anyone tell what is wrong in this code.... it is giving write answer on ideone but
spoj is showing wrong answer
#include <stdio.h>
int main(void) {
int t,r,c;
long k,n,no;
scanf("%d",&t);
while(t--)
{
scanf("%ld",&k);
if(k<=1000000)
{
c=0;
while(c==0)
{
++k;
n=k;
see more

Reply Share
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

7/15

05/10/2016

Reply Share

Given a number, nd the next smallest palindrome - GeeksforGeeks

deeksha garg > deeksha garg a year ago

Can anyone plzz tell my mistake in this program... I have being trying it for 3 days
still its showing wrong ans on spoj

Reply Share
Manraj Singh > deeksha garg a year ago

Hey! The question says there are nearly 1000000 digits as input! And that
won't t in long int. Use a string.

Reply Share
deeksha garg > Manraj Singh a year ago

But how can I use string in c... I have to take an char array in it and it
will increase the memory... Can u plzz help

Reply Share
Manraj Singh > deeksha garg a year ago

Yes it will increase memory but you have more than enough memory
to use. http://ideone.com/LWzgW7

Reply Share
deeksha garg > Manraj Singh a year ago

Ya but string array if we take then how we will perform integer


function on it

Reply Share
Manraj Singh > deeksha garg a year ago

Like this http://ideone.com/vy5qi6

Reply Share
Markandayan P a year ago

for all 9's number ... just add 2


1

Reply Share

deepak a year ago

this code is not working on spoj...saying wrong answer


plzzzz help...its long 4 hour of head ache in nding y it is wrong
#include<stdio.h>
int main()
{
int a[10],t,i,count,d,num,found,num2;
scanf("%d",&t);
while(t--)
{ found=0;
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

8/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

{ found=0;
scanf("%d",&num);
while(found==0)
{ i=0;
see more

Reply Share
Md Farooq 2 years ago

awesome explanation

Reply Share
manas 2 years ago

what about this solution is not this right?comment plz


#include<stdio.h>
int revese(int);
int main()
{
int num,rev,x;
rev=0;
printf("enter the non");
scanf("%d",&num);
num=num+1;// here i increase the num by 1
while(x=1)
see more

Reply Share
Uma Kanth > manas a year ago

This does not work for numbers greater than the int range. Consider a test case
with input more than 1000000 digits.

Reply Share
Aman Mittal 2 years ago

May be Complexity is high but works for every case. . .


public class NextSmallestPallindrome {
private static int[] ndPallindrome(int[] no) {
int number = 0;
for (int i = 0; i < no.length; i++) {
number = number * 10 + no[i];
}
number = number + 1;
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

9/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

number = number + 1;
String string = Integer.toString(number);
int num[] = new int[string.length()];
for (int i = 0; i < string.length(); i++) {
num[i] = string.charAt(i);
num[i]-=48;
}
int check = 0;
if (num.length > 2) {
if (num.length % 2 != 0) {
for (int i = 0; i <= (num.length / 2) + 1; i++) {
see more

Reply Share
Rohin Mehra 2 years ago

Please check more simpler solution.


http://ideone.com/VKuY1k

Reply Share
Kenneth 2 years ago

Here is my iterative solution and tests, where the input is an integer number, rather than a
digit array. The time complexity is O(d) and space complexity is O(1), where d is the digit
count of the input integer.
http://ideone.com/1ntnAa
3

Reply Share

kaushik Lele 2 years ago

@geeksforgeeks
Please nd below recursive approach for nd the next smallest palindrome"
Algorithm :If number is all 9's say 99 then then its palindrome will be 101. For 999 answer is 1001 and
so on
For other cases
if input is 1356 then we will start with rst & digit same as input 1 _ _ 1
Now we will call same function to get palindrome of internal number by striping rst and
last digit viz. 35.
So function call for 35 will return 44
So answer for 1356 is 1 4 4 1
Now if number is 1996 the we will start with 1 _ _ 1
Now we will call same function to get palindrome of internal number by striping rst and
last digit viz. 99.
So function call for 99 will return 101
So it returned palindrome of length more than 2; it means we should increase outer digit to
make it 2 _ _ 2
And we should ll it up with zeros.
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

10/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

Thus answer for 1996 is 2002


Code is shared at
http://ideone.com/3sGpMr
1

Reply Share
Soumik Chatterjee > kaushik Lele 2 years ago

Your algorithm won't work for numbers such as 7992.It will give 8008, whereas
7997 should be the answer.
2

Reply Share
Aneek Roy > Soumik Chatterjee a year ago

bhai _/_

Reply Share
kaushik Lele > Soumik Chatterjee 2 years ago

You are right. Need to modify code for such case.

Reply Share
Sahil > kaushik Lele a year ago

You missed few cases. I have used a similar approach which cover
all the cases. http://ideone.com/ZTB9ds

Reply Share
Karshit Jaiswal 2 years ago

Very poorly explained approach. By only looking at the approach you cannot code it.
Please explain the 2 sub cases properly with more vivid examples.

Reply Share
kaushik Lele > Karshit Jaiswal 2 years ago

Can you check my approach above. A recursive and easy to understand.

Reply Share
Basant 2 years ago

How to calculate next palindrome after 119921 ?

Reply Share
Ekta Goel > Basant 2 years ago

i and j after comparing the middle digits are 1 and 4, and now a[1]<a[4], hence,=""
increment="" the="" middle="" digit="" i.e.a[2]="" and="" propagate="" the=""
carry="" forward="" and="" simultaneously="" copy="" the="" left="" half="" to=""
its="" right="" half.="" i.e.="" 1(1+1)0="" 921,="" copying="" now="" to="" its=""
right="" half="" we="" get="" 120021="" as="" the="" next="" palindrome.="">

Reply Share
Guest > Basant 2 years ago

i and j after comparing the middle digits are 1 and 4, and now a[1]<a[4], hence,=""
increment="" the="" middle="" digit="" i.e.a[2]="" and="" propagate="" the=""
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

11/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

carry="" forward="" and="" simultaneously="" copy="" the="" left="" half="" to=""


its="" right="" half.="" i.e.="" 1(1+1)0="" 921,="" copying="" now="" to="" its=""
right="" half="" we="" get="" 120021="">

Reply Share
Israil Bony 2 years ago

this is my code if any wrong in my code plz help me


#include<bits stdc++.h="">
#dene rep(i,n) for(int i=0;i<n;i++) #dene="" mem(x,y)="" memset(x,y,sizeof(x));=""
using="" namespace="" std;="" long="" long="" a[100000];="" int="" main()="" {=""
long="" long="" int="" i,j,k,n,m="0,c=0,p,l;" cin="">>n;
for(i=1;i<=n;i++)
{
cin>>a[i];
}
//c=ceil(log2(n));
//cout<<c<<endl; m="i/2;" if(n%2="=0)" {="" j="m+1;" }="" else="" j="m;" m="ceil(n/2);"
for(i="m;i">0;i--)
{
if(a[i]!=a[j])
{
if(a[i]>a[j])
{
see more

Reply Share
sharath 2 years ago

i have written a code..works ne in my pc .. but while submitting in spoj


http://www.spoj.com/problems/P... ..i'm getting a error "SIGABRT"
any help would be greatly helpfull ..thank you :)
#include<iostream>
#include <sstream>
#include <string>
using namespace std;
bool is_palin(string str) //returns false if a plaindrome and a true if not a palindrome
{
int len = str.length();
bool temp = true;
for (int i = 0; i<len 2;="" i++)="" {="" if="" (str[len="" -="" i="" -="" 1]="=" str[i])="" {=""
see more

Reply Share
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

12/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

typing.. 2 years ago

I have O(logn) solution with no lengthy code and testing only three conditions-1.whether it is 1 digit number? -- O(1)
2.whether it contain all 9 or not? -- O(logn)
3.otherwise. -- O(logn)
here is code-#include<stdio.h>
void print(int arr[], int u)
{
int i;
printf("Next smallest palindrome is :n");
for(i=0;i<u;i++) {="" printf("%d="" ",arr[i]);="" }="" printf("n");="" }="" void=""
see more

Reply Share
Saurabh > typing.. 2 years ago

Please share the code through ideone link.

Reply Share
typing.. > Saurabh 2 years ago

Here is the link : http://ideone.com/8rnDQy

Reply Share
kinshuk chandra 2 years ago

Here is my basic algo:


1. Break the number into 2 halfs "2133" = "21","33"
2. Now if rst half is greater than 2nd half AND rst half is same
size as 2nd half AND reverse(rst) is greater than 2nd half, then
nextPalindrome = rst + reverse(rst), otherwise go to step 3.
Example 783322 = 783 + 387 = 783387. However 2133 wont hold. Nor will
1001, as rst = 10, and last = 01 = 1
3. Increment the rst half by 1,
rst = rst+1
nextPalindrome = rst + reverse(rst)
Example 2133, rst = 21, rst+1 = 22, Now concat rst and reverse rst = 2222
Here is my post http://k2code.blogspot.in/2014...

Reply Share
sammyblr 2 years ago

http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

13/15

05/10/2016

sammyblr 2 years ago

Given a number, nd the next smallest palindrome - GeeksforGeeks

Check out this code for nding next smallest palindrome.


http://wp.me/3bJAF

Reply Share
rahul 3 years ago

@GEEKSforGeeks
We can have one check before the code mirror left to right
i.e.
if(!leftsmaller)
mirror left to right;
else
increment middle case
This would save lot of time for the cases in which we are increment middle digit as for this
copying left to right is an unnecessary steps.
thnx
2

Reply Share

Preeti 3 years ago

Next Palindrome for 9 4 1 8 7 9 7 8 3 2 2 should be 9 4 1 8 7 9 7 8 1 4 9. Right?


1

Reply Share
Rahul > Preeti 3 years ago

No its 9 4 1 8 8 0 8 8 1 4 9
1

Reply Share

Thunderbird 3 years ago

http://www.codechef.com/viewso...

Reply Share
Akash Verma 3 years ago

wonder if the so-long code eects the time complexity!

Reply Share
Sri Hari > Akash Verma 3 years ago

Yeah totally!!
Not the execution time complexity but the implementation time complexity.
6

Reply Share
Load more comments

Subscribe d Add Disqus to your site Add Disqus Add

Privacy

http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

14/15

05/10/2016

Given a number, nd the next smallest palindrome - GeeksforGeeks

@geeksforgeeks, Some rights reserved Contact Us! About Us! Advertise with us!

http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/

15/15

Potrebbero piacerti anche