I am trying to solve SPOJ problem 5: find the next largest integer “palindrome” for a given input; that is, an integer that in decimal notation reads the same from left-to-right and right-to-left.
Please have a look of the question here
Instead of using brute force search, I try to calculate the next palindrome. But my code still returns TLE (that is, Time Limit Exceeded) and I am frustrated… Would you mind giving me a hint?
Here is my code in python 3.x
if __name__ == '__main__':
n = int(input())
for i in range(n):
string = input()
length = len(string)
ans = ""
if length %2 == 0 :
half = length // 2
str_half = string[0:half]
ans = str_half + str_half[::-1]
if(ans <= string):
str_half = str(int(str_half) + 1)
ans = str_half + (str_half[0:half])[::-1]
print(ans)
else:
half = length // 2
str_half = string[0:half]
ans = str_half + string[half] + str_half[::-1]
if(ans<= string):
str_half = str(int(str_half+string[half]) + 1)
ans = str_half + (str_half[0:half])[::-1]
print(ans)
The input can be long. The problem statement says “not more than 1000000 digits”. So probably there are a couple of test cases with several hundred thousand digits. Splitting such a string in halves, reversing one half and appending them does take a little time. But as far as I know, Python’s string handling is pretty good, so that’s only a small contribution to the problem.
What is taking a long time is converting strings of such length to numbers and huge numbers to strings. For
K = 10 ** 200000 + 2, the stepstr_half = str(int(str_half+string[half]) + 1)alone took almost a second here. It may be faster on your computer, but SPOJ’s machines are quite slow, one such occurrence may push you over the time limit there.So you have to avoid the conversions, work directly on the string representations (mutable lists of digits).