LeetCode: Palindrome Number

Return true if an integer is a palindrome.

Posted on LeetCode Python

See original problem on leetcode.com

Difficulty: Easy

Pythonic Solution

This has a very easy Pythonic solution. Since the string operations in Python are highly optimized, this solution performs very well. Convert the integer to a string and compare it to its reverse.

Runtime

0 ms | Beats 88.88%

class Solution:
def isPalindrome(self, x: int) -> bool:
# Convert the integer to a string
s = str(x)
# Compare the string to its reverse
return s == s[::-1]

Two-Pointer Solution

You can also use a two-pointer approach. Set the first pointer to the start of the string and the second pointer to the end of the string. Compare the characters at each pointer. If the characters do not match, immediately return False. If they match, move the first pointer forward and the second pointer backward, and continue comparing until the pointers meet or cross. If all characters match, return True.

This solution is slower than the Pythonic solution, but it is a good demonstration of the two-pointer technique.

Runtime

3 ms | Beats 88.13%

class Solution:
def isPalindrome(self, x: int) -> bool:
# Convert the integer to a string
s = str(x)
# Initialize two pointers
left = 0
right = len(s) - 1
while left < right:
# If the characters at the pointers do not match, it's not a palindrome
if s[left] != s[right]:
return False
# Move the pointers closer to the center
left += 1
right -= 1
return True