Flipkart Interview Question for Software Engineer / Developers






Comment hidden because of low score. Click to expand.
1
of 3 vote

1. Get the num till half of the number of digit of given num.
2. Add 1 in to it.
3. Reverse the num obtained in step 2.
4. Append the numbers obtained in 2 and 3.
***Take care of odd and even num of digits.

int nextPalindromInt(int inPalindromeInt)
{
	int numOfDigit=0, placeValue=1;
	int num=inPalindromeInt, halfNum=0, i;
        int isAll9Digit=1;
	if((num>=-9)&&(num<=9)) 
	     return num;
	/*Get Total num of digit and place value of most significant digit*/
	while(num)
	{
		numOfDigit++;
		if(((num%9)!=0)||((num%10)==0))
		{
			isAll9Digit=0;
		}
		num=num/10;
		placeValue = placeValue*10;
	}
	if(((isAll9Digit==1)&&(inPalindromeInt>0))||
	    ((((inPalindromeInt+1)%100)==0)&&(inPalindromeInt<0)))
	{
		return inPalindromeInt+2;
	}
	i=(numOfDigit>>1)+((numOfDigit%2)?1:0);
	num=inPalindromeInt;
	placeValue=placeValue/10;
    /*Get the num till half of the number of digit*/
	while(i)
	{
		halfNum	= halfNum*10 + num/placeValue;
		num=num%placeValue;
		placeValue = placeValue/10;
		i--;
	}
	/*Add one in halfnum, get next palindrome by appending 
	    halfNum in to halfNum in reverse manner*/
	halfNum=halfNum+1;
	num=halfNum;
	if(numOfDigit%2)
	{
		num=halfNum/10;
	}
	while(num)
	{
		halfNum=halfNum*10 + num%10;
		num=num/10;
	}
	return halfNum;
}

- Tulley April 09, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How about if the number is n digit long. How would you store the number?

- Jit April 09, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I assumed that there wont be overflow and the number is palindrome.
Dealing with a number which cant be expressed in 32 or 64 bit of architecture is another area of research and many papers had been already published but in the same question if numbers are represented as string then above algorithm holds with few modifications.

- Tulley April 09, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Tulley I have observed that you have developed a habit of posting wrong solutions on most of the problems posted on the website.. please spend sometime in making sure that your solutions work .. will it work for 99->101

- Anonymous April 09, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Anonymous: Thanks for yr valuable suggestion. It always happens that u r not able to identify all bugs in yr code. I love to put code here for discussions, suggestions and taking input from many minds :)
By the way I've edited the above code n hope it works for all the cases now.

- Tulley April 09, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@tully i am assuming that in all given solution urs is working fine so could un plz tell me what to do if number is big like 15 digit no. 123456789123456
the how to find next palindrome of it..using int & long its giving error ..?? i mean integer overflow..??

- Algoseekar April 21, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@tully i am assuming that in all given solution urs is working fine so could un plz tell me what to do if number is big like 15 digit no. 123456789123456
the how to find next palindrome of it..using int & long its giving error ..?? i mean integer overflow..??

- Algoseekar April 21, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hi Algoseekar:
if u have data type (built in or user defined) to take input for big integers then same u can use in my code for processing and output.
if u r taking the input as string of digits then one of the solution given below is extremely good and clean:
ideone.com/ElXqx given by some anonymous.

- Tulley April 21, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@tulli your algor & program wont run for number 808 its giving 8118 as o/p but right ans shoud be 818...isn't it..??

- Algoseekar May 28, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Spec in Haskell

next :: Int -> Int
next p = palindromes [p+1..] where
palindromes (x:xs) =
let str = show x in
if str == reverse str then x else palindromes xs

- ruk April 08, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Spec in Haskell

next :: Int -> Int
next p = palindromes [p+1..] where
  palindromes (x:xs) = 
    let str = show x in 
      if str == reverse str then x else palindromes xs

- ruk April 08, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<conio.h>
int main()
{
int n;
int u,l,num,count1=0,b,count2=0;
int a=1;
int sum=0;
int sum2=0;
scanf("%d",&n);
num=n;
while(a<n)
{
a=a*10;
++count1;
}
a=a/10;
if(count1%2==0)
{
u=1;
}
else
{
u=2;
}
b=a;
while(num!=0)// loop to add 11 to the middle 2 for even and 1 for odd.
{
if((u==1)&&((count2==(count1/2-1))||(count2==count1/2)))
{
sum=sum+b;
sum2=sum2+(num/b)*b;
printf("\n%d",sum);
if(count2==count1/2)
{break;}
}
if((u==2)&&(count2==count1/2))
{
sum=sum+b;sum2=sum2+(num/b)*b;printf("\n%d",sum);break;
}
num=num%b;
b=b/10;
++count2;
}
if(sum2%9==0)// cheking the case of 999 0r 9999
{
n=n+2;
}
else
{
n=n+sum;
}
printf("next palindrome is: %d",n);
getchar();
getchar();
return 0;
}


The code is not proper ly formatted, but works well try 2 understand it. Plz post any problem in it.

The concept is if the number of digits is even : add 11 to the middle 2 numbers
" "odd : add 1 " " number
Check foe if the addition does not cause any change in the number of digits for example:

999 + 010 = 1000 not a palindrome the ans should be 1001.

- Nascent_coder April 09, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Replace:
if(sum2%9==0)// cheking the case of 999 0r 9999

with :
if(sum2%9==0 && (sum2!=0))// cheking the case of 999 0r 9999

- Nascent_coder April 09, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

check my solution here ideone.com/ElXqx

tested input cases:
0 -> 1
9 -> 11
999 -> 1001
9999 -> 10001
10001 -> 10101
100001 -> 101101
52960 -> 53035
4998 -> 5005

- anonymous April 10, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

+1 comprehensive and neat solution seems to be 100% correct, unlike the 90% of the users on CC who post ad-hoc idea/code only.

- LOL April 11, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

data wrong!
52960 -> 53035 ==> 52925 -> 53035
4998 -> 5005 ==> 4994 -> 5005

- lshmouse April 12, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Its not working for -ve numbers, LOL :)

- Verma April 12, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@lshmouse: I think you probably need to understand the problem first before looking at input/output case. Question is asked for NEXT LARGEST palindrome, NOT NEAREST palindrome. Hence, 53035 is NEXT LARGEST palindrome of 52960, and 5005 is NEXT LARGEST palindrome of 4994. An advice for you, if you DON'T understand a question, first ask others to clarify that. No offense.

@Verma: palindrome is never considered as +ve/-ve numbers. I doubt where from you got this information.
Of course, if you need to get NEXT SMALLEST palindrome, you can easily tweak my idea to get the NEXT SMALLEST. Try it as an exercise to show your understanding. Thanks.

- anonymous April 12, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Anonymous
y next smallest?
if -101 is a palindrome integer then according to the question next largest palindrome integer is -99.
Have a look on this "acmicpc-live-archive.uva.es/nuevoportal/data/p2552.pdf". It talks about negative palindrome integres. Hope u'll correct your code.

- Verma April 12, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

You should understand now why I asked to tweak my code to get NEXT SMALLEST palindrome. For example, Next largest palindrome of -101 = -(next smallest palindrome of 101). Got it?

- anonymous April 12, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

How about this?.

int nextPalindromInt(int inPalindromeInt)
{
int numOfDigits = 0, halfDigits=0, secondHalf=0, firstHalf = 0;

if ((inPalindromeInt >= -9) && (inPalindromeInt <= 9))
return inPalindromeInt;

/*Get Total number of digit */
numOfDigits = (int)(Math.Log10(inPalindromeInt) / Math.Log10(10) + 1);

halfDigits = numOfDigits / 2;

firstHalf = (int)(inPalindromeInt / Math.Pow(10,(numOfDigits/2))) + 1;

if (inPalindromeInt % 9==0 && halfDigits >1)
secondHalf = firstHalf / 100;
else if((inPalindromeInt % 9==0 && halfDigits ==1) || (numOfDigits % 2 == 1))
secondHalf = firstHalf/10;
else if (numOfDigits % 2 == 0)
secondHalf = firstHalf;

firstHalf = (firstHalf * (int)Math.Pow(10, halfDigits));

while (secondHalf > 0)
{
firstHalf += (int)((secondHalf % 10) * (int)Math.Pow(10, halfDigits - 1));

halfDigits--;
secondHalf /= 10;
}

return firstHalf;
}

- N.M April 11, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Flip all de 9s starting from de middle on both sides to 0.increment de first non 9 on both sides...u may need to add trailing or leading zeros

- Sathya April 11, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Does your solution say ANYTHING about a REAL solution?

Freaking stupid, why you post same message twice :-O

- LOL April 11, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@LOL: my browser refreshed twice while posting...i m sure u dont understand ANYTHING of wat i m saying lets see if some illustration can help you
12344321->start from middle, no 9s, increment 1st non-9 ie both 4's 12355321 is the next palin
123999321->next palin->124000421
129921->130031
string of all 9's is a corner case and u should output 1 less 0 9->11,99->101 etc

- Sathya April 12, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Thanks for some clarification. I'd suggest you to clarify at least to this level, and to avoid "de" in place of "the". I know it takes more time, but in that way you could develop better skill to explain your idea clearly to interviewers. No offense pls.

- LOL April 12, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Flip all de 9s starting from de middle on both sides to 0.increment de first non 9 on both sides...u may need to add trailing or leading zeros

- Sathya April 11, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class nextPalindrome{
	public static void main(String[] args){
		System.out.println(findNextPalindrome(222));
	}
	public static int findNextPalindrome(int num){
		if(num+1 == (int)Math.pow(10,(int)Math.log10(num+1)))
			return num+2;
		int numDigits = (int)Math.log10(num) + 1 ;
		int firstHalf = num/(int)Math.pow(10,numDigits/2);
		firstHalf +=1;
		String str = (new Integer(firstHalf)).toString();
		if(numDigits%2 == 0){
			str = str + new StringBuffer(str).reverse();
		}
		else{
			str = str + new StringBuffer(str.substring(0,str.length()-1)).reverse();
		}
		int result = Integer.parseInt(str);
		return result;
	}
}

- Abhishek April 13, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this will not work with 1221

- iamnotiam April 20, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*Given a palindrome find an algorithm to get the next palindrome*/

int getNextBigPalindrome(int palin){
	String palinString = new String(palin);
	int numDigits = palinString.length();

	//abcdefgh = 8 ==> abc
	//abcd i efgh = 9 ==> abcd
	String leftPart = numDigits%2 == 0 ? palinString.subString(0, numberDigits/2-1): 
										palinString.subString(0, numberDigits/2);
	
	//abcdefgh = 8 ==> de
	//abcd i efgh = 9 ==>i
	String centerPart = numDigits%2 == 0 ? palinString.subString(numberDigits/2-1, 
																	numberDigits/2+1): 
										palinString.subString(numberDigits/2, 
																	numberDigits/2+1);
																	
	//abcdefgh = 8 ==> fgh
	//abcd i efgh = 9 ==> efgh	
	String rightPart = numDigits%2 == 0 ? palinString.subString(numberDigits/2+1,numDigits): 
										palinString.subString(numberDigits/2+1, numDigits);
			
    int leftInt = String.parseInt(leftPart);
	int centerInt = String.parseInt(centerPart);
	int rightInt = String.parseInt(rightPart);
	
	
	if(centerPart.length == 1){
		if(centerInt != 9){
			//Case of 111, 121, 131, 141, 151, 161, 171, 181
			centerInt += 1;
			centerPart = new String(centerInt);
		}else{
			//Case of 191
			centerPart = "0";
			leftInt++;			
			leftPart = new String(leftInt);
			rightPart = leftPart.reverse();
		}
	}else{
		if(centerInt != 99){
			//Case of 1111, 1221, 1331, 1441, 1551, 1661, 1771, 1881
			centerInt +=11;
			centerPart = new String(centerInt);
		}else{
			//Case of 1991
			centerPart = "00";
			leftInt++;
			leftPart = new String(leftInt);
			rightPart = leftPart.reverse();
		}
	}	
	return String.parseInt(leftPart + centerPart + rightPart);
}

- iamnotiam April 20, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

<pre lang="" line="1" title="CodeMonkey18529" class="run-this">/*
For odd no of digits, icrement the left half (including middle element) and reverse the no (leaving the rightmost) and add it to the incremented no
For even no of digits, simply take left half, increment it by one, reverse the incremented no and add it to the right
*/
public static Integer nextLargestPalindrome(Integer no){
String s = no.toString();
int len = s.length();
if(len % 2 == 1){
String left = s.substring(0,len/2 + 1);
int x = Integer.parseInt(left)+1;
return Integer.parseInt(x+reverse(x/10));
}
else{
String left = s.substring(0,len/2);
int x = Integer.parseInt(left)+1;
return Integer.parseInt(x+reverse(x));
}
}

public static String reverse(Integer x){
return (new StringBuffer(x.toString())).reverse().toString();
}
</pre>

- Anonymous June 16, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The algorithm for the above problem is :
(1) Take the number in form of string eg: 86123,41923
(2) Now take the first half of the string // reverse it and copy to generate a palindrome number eg: 8624--> 8668 86123--> 86168 41923 ---> 41914 4295-->4224
(3) When the generated number is larger than your current number it is the next palindrome.
(4) In case if it is not larger than the current number then add 1 to the middle digit eg: since 4224 is smaller than the original 4295 we add digit 1 and copy the first half of the string after reversing . So 4224 ---> 4334 which happens to be the next palindrome.
There are cases like when generated 41914 is smaller than 41923 then we add 1 and it converts to 41014. In these cases we have to carry 1 to the other half and then reverse + copy. So 41914 --> 42024. Similarly 999 ---> (100)9 --> copy the first half // reverse and paste --> 1001
You may have to take special care of single digit cases like 9 --> 10 --> 11

- shadow_warrior June 18, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<conio.h>
unsigned int nextPalin(unsigned int num){
    int flag=1,a[10],dig=0,mid,offset=0;
    unsigned int cnum;
    cnum=num;
    while(cnum!=0){
                   a[dig]=cnum%10;
                   cnum=cnum/10;
                   dig++;
                   if(a[dig-1]!=9){
                                 flag=0;
                                 break;
                                 }
                   }
    if(flag){
             return num+2;
             }
             else{
                  while(cnum!=0){
                                 a[dig]=cnum%10;
                                 cnum=cnum/10;
                                 dig++;
                                 }
                  mid=dig/2;
                  mid--;
                  if(a[mid]!=a[mid+1]){
                                       if(a[mid+1]==9)
                                       {
                                                      a[mid]++;
                                                      a[mid+1]=0;
                                                      a[mid+2]++;
                                                      }
                                                      else{
                                       a[mid+1]++;}
                                       }
                  else{
                       while(a[mid-offset]==9){
                       a[mid-offset]=0;
                       a[mid-offset+1]=0;
                       offset++;
                       }
                       a[mid-offset]++;
                       a[mid+offset+1]++;
                       }
                       int prod=1;
                  for(int i=0;i<dig;i++){
                          cnum=cnum+a[i]*prod;
                          prod*=10;
                          }
                  }
                  return cnum;
    }
int main(){
  unsigned int num;
  printf("Enter the number\n");
  scanf("%d",&num);
  num=nextPalin(num);
  printf("The next palindrome is: %d",num);
  getch();
  return 0;
  }

- Vikas September 22, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Case I: The given number is a palindrome..eg: 1234321 then simply increment the center digit by 1 i.e the ans is 1235321

Case II: The given number is not a palindrome:

Subcase 1: The number to the left of the middle digit is greater than the number on the right eg:2194135 (here 219 > 135) then,reverse the left side numbers and replace the right side numbers with them, therefore the ans will be 2194912.

Subcase 2:The number to the right of the middle digit is greater than the number on the left eg:1354219 then,
then increment the middle digit by 1 and then reverse the left side numbers and replace the right side numbers with them. Therefore the answer would be 135 5(middle digit incremented) 531(reversed), resulting in 1355531, which is the next palindrome.
Note: in case the middle digit is 9 then incrementing it would make it 10, so put 0 instead of 9 and increment the first right and left neighboring digit of 9 by 1.

- Chuchu November 02, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

what if the number has even number of digits.
eg. 131219
??

- shivam July 08, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Case1: odd number of digits
case1a: if middle digit is not 9 then increment the middle dight by 1.
case 1b: if middle digit is 9, make it 0 and add 1 to left substring of number, reverse and append it as right substring of number.

case 2: even number of digits
Add 1 to left substring of number, reverse and append it to get next palindrome.

- gaurav gupta January 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Scala:

def nextPalindrome(n: Int): Int = {
 def isPalindrome(e: Int) = e.toString == e.toString.reverse 
 var curr = n+1
 while(!isPalindrome(curr)){
  curr = curr+1
 }
 curr
}

scala> nextPalindrome(9)
res0: Int = 11

scala> nextPalindrome(101)
res1: Int = 111

- rbsomeg March 10, 2013 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More