Given a string, determine if it is a palindrome.
A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward
Example 1:
Input: "madam racecar madam" Output: true
Example 2:
Input: "abcbx" Output: false
Your algorithm should run in O(n) time and use O(1) extra space.
The core challenge of this problem is to determine if a given string reads the same backward as forward. This is significant in various applications such as text processing, data validation, and more. A common pitfall is to overlook the need for an efficient solution that runs in linear time and uses constant space.
To solve this problem, we can use a two-pointer technique:
A naive solution would involve reversing the string and comparing it to the original. However, this approach uses O(n) extra space and is not optimal.
The two-pointer technique is optimal because it runs in O(n) time and uses O(1) extra space. Here’s how to implement it:
i
at the start (0) and j
at the end (n-1) of the string.i < j
:
s[i] != s[j]
. If true, return False
.i
and decrement j
.False
, return True
.def is_palindrome(s: str) -> bool:
# Initialize two pointers
i, j = 0, len(s) - 1
# Loop until the pointers cross
while i < j:
# If characters at i and j are not equal, it's not a palindrome
if s[i] != s[j]:
return False
# Move the pointers towards each other
i += 1
j -= 1
# If we complete the loop without finding a mismatch, it's a palindrome
return True
# Test cases
print(is_palindrome("madam racecar madam")) # Output: True
print(is_palindrome("abcbx")) # Output: False
The time complexity of this approach is O(n) because we are traversing the string once. The space complexity is O(1) as we are using only a constant amount of extra space for the pointers.
Consider the following edge cases:
True
as an empty string is trivially a palindrome.True
as a single character is a palindrome.To test the solution comprehensively, consider the following test cases:
When approaching such problems, consider the following tips:
Understanding and solving palindrome problems is crucial for various applications. The two-pointer technique provides an efficient solution with O(n) time complexity and O(1) space complexity. Practice and explore further to master such problems.
For further reading and practice, consider the following resources: