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.
i
starting from the beginning (i = 0
) and one index variable j
starting from the end of the string (j = n - 1
).
How should we move these pointers throught the algorithm?
i < j
:
s[i] != s[j]
and if so, we conclude the string is not a palindrome and return false
.i
one step to the right.j
one step to the left.i
became greater than or equal to j
and we haven't returned false, then we can conclude the string is a palindrome and return true
.
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 O(n) time and uses O(1) extra space.
To solve this problem, we can use a two-pointer technique. One pointer starts at the beginning of the string, and the other starts at the end. We compare the characters at these pointers and move them towards the center. If all corresponding characters are equal, the string is a palindrome.
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 optimized solution uses two pointers:
Here is a step-by-step breakdown of the algorithm:
#include <iostream>
#include <string>
bool isPalindrome(const std::string& s) {
int i = 0;
int j = s.length() - 1;
while (i < j) {
// Compare characters at i and j
if (s[i] != s[j]) {
return false; // Not a palindrome
}
i++;
j--;
}
return true; // Is a palindrome
}
int main() {
std::string str1 = "madam racecar madam";
std::string str2 = "abcbx";
std::cout << std::boolalpha; // Print bools as true/false
std::cout << "Is \"" << str1 << "\" a palindrome? " << isPalindrome(str1) << std::endl;
std::cout << "Is \"" << str2 << "\" a palindrome? " << isPalindrome(str2) << std::endl;
return 0;
}
The time complexity of this approach is O(n) because we traverse the string once. The space complexity is O(1) as we only use a constant amount of extra space for the pointers.
Consider the following edge cases:
To test the solution comprehensively, consider the following test cases:
When approaching such problems, consider the following tips:
In this blog post, we discussed how to determine if a string is a palindrome using an efficient O(n) time and O(1) space algorithm. Understanding and solving such problems is crucial for improving algorithmic thinking and coding skills.
For further reading and practice, consider the following resources: