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 even in some algorithms related to DNA sequencing.
Common pitfalls include not considering spaces, punctuation, or case sensitivity. For simplicity, we assume the input string is case-sensitive and includes spaces.
To solve this problem, we can use a two-pointer technique:
This approach ensures we only traverse the string once, achieving O(n) time complexity with O(1) extra space.
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
./**
* Function to check if a given string is a palindrome
* @param {string} s - The input string
* @return {boolean} - True if the string is a palindrome, false otherwise
*/
function isPalindrome(s) {
// Initialize two pointers
let i = 0;
let j = s.length - 1;
// Loop until the pointers meet
while (i < j) {
// If characters at pointers do not match, return false
if (s[i] !== s[j]) {
return false;
}
// Move the pointers
i++;
j--;
}
// If all characters matched, return true
return true;
}
// Example usage:
console.log(isPalindrome("madam racecar madam")); // Output: true
console.log(isPalindrome("abcbx")); // Output: false
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:
Examples:
isPalindrome("") // true isPalindrome("a") // true isPalindrome("A man, a plan, a canal, Panama") // false (case-sensitive and includes spaces)
To test the solution comprehensively, consider using a variety of test cases:
Using a testing framework like Jest can help automate and manage these tests.
When approaching such problems:
Understanding and solving palindrome problems is crucial for developing strong problem-solving skills. This problem teaches the importance of efficient algorithms and space optimization. Practice and exploration of similar problems can further enhance these skills.
For further reading and practice: