Wrong answer in palin-the next palindrome

    #include <iostream>

using namespace std;
int palindrome(long long int);
int main() {
// your code goes here
int test;

    cin>>test;
    while(test--)
    {
           long long int k=0;
            cin>>k;
            for(long long int i=k+1;;i++)
            {
                    if(palindrome(i)==1)
                    {
                    cout<<i<<endl;
                            break;
                    }
            }
    }
    return 0;

}
int palindrome(long long int x)
{
int arr[7],y=0,f=0;
for(int i=0;i<7;i++)
{
arr[i]=x%10;
x=x/10;
if(x==0)
{ y=i;
break;
}
}
for(int j=0;j<y;j++)
{
if(arr[j]==arr[y-j])
f += 1;
}
if(f==y)
return 1;
else return 0;
}
i cannot find any wrong output in the above code but on submission it says wrong answer.Please help me out in finding error in above code.(But the above code was accepted in hackerrank).

Delete this code and write on ideone (online compiler) and post the link here :slight_smile:

Hello @harsh_kumar123

Problem Link

Input may contain 1000000 digits which cannot be stored using β€˜long long’.

Also your method of looping through numbers and checking for palindrome is inefficient. You need to optimize your solution!

Refer this article for optimized solution

My AC Solution

1 Like

The video Solution of this problem can be found here: How to solve the The Next Palindrome | PALIN | Codechef | Competitive coding | C++ - YouTube

for _ in range(int(input())):
s=input()
if len(s)>1:
j=[i for i in s]
h=[i for i in s]
if len(s)%2==0:
for i in range(len(s)//2):
j[i]=j[len(s)-i-1]
h[len(s)-i-1]=h[i]
else:
for i in range(len(s)//2-1):
j[i]=j[len(s)-1-i]
h[len(s)-1-i]=h[i]
g=’’.join(j)
p=’’.join(h)
if len(s)%2==1:
d=s[:len(s)//2+1]
if d!=β€˜9’*(len(s)//2+1):
d=int(d)+1
d=str(d)
k=d[::-1]
for i in range(1,len(k)):
d=d+k[i]
else:

            d=int(d)+1
            d=str(d)
            k=d[::-1]
            for i in range(2,len(k)):
                d+=k[i]
    else:
        d=s[:len(s)//2]
        if d!='9'*(len(s)//2):
            d=int(d)+1
            d=str(d)
            k=d[::-1]
            for i in range(len(k)):
                d=d+k[i]
        else:

            d=int(d)+1
            d=str(d)
            k=d[::-1]
            for i in range(1,len(k)):
                d+=k[i]
    d=int(d)
    g=int(g)
    p=int(p)
    #print(d,g,p)
    f=int(s)
    l=[]
    for i in [d,g,p]:
        if i>=f:
            l.append(i)
    #print(l)
    l.sort()
    for i in l:
        if i>f:
            f=i
            break

    print(f)
else:
    print(11)    

can anyone tell me why it is getting TLE