I have solved the palindrome question on LeetCode today, but I wasn't happy with the original solution - I used strings, it worked slowly and used a lot of memory.
So I rewrote the answer using a dictionary approach instead knowing that looking up a value in a dictionary has lower time complexity than searching through a list, but the results were strange - my latest answer is much better in terms of memory use (better than 94.65% of other submissions), but it became significantly slower. As you can see in the image below, my last submission is much slower than the first, but memory use has improved a lot:
My original solution was this:
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
if len(s) == 1:
palindrome = True
i = int(len(s)/2)
for p in range(i):
if s[p] != s[-(p+1)]:
return False
else:
palindrome = True
return palindrome
And the updated version is:
class Solution:
def isPalindrome(self, x: int) -> bool:
s = {i:j for i,j in enumerate(str(x))}
i = (max(s)+1)//2
if max(s)+1 == 1:
return True
for p in range(i):
if s[p] != s[max(s)-p]:
return False
else:
palindrome = True
return palindrome
Can anyone explain why the latest version is so much slower? I thought it should be faster...
What should I change to improve the speed?
EDIT:
New version based on @hjpotter comment. Now I only have 1 call to max()
in the entire script and yet it's even worse - 168ms and 13.9 Mb. I don't understand what's happening here:
class Solution:
def isPalindrome(self, x: int) -> bool:
s = {i:j for i,j in enumerate(str(x))}
m = max(s)
i = (m+1)//2
if m+1 == 1:
return True
for p in range(i):
if s[p] != s[m-p]:
return False
else:
palindrome = True
return palindrome
max
\$\endgroup\$ceil
,log10
, and some arithmetic. \$\endgroup\$