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 problem requires us to determine if a given string is a palindrome. A palindrome is a sequence of characters that reads the same backward as forward.
Input: A string s
.
Output: A boolean value true
if the string is a palindrome, otherwise false
.
Constraints:
Example:
Input: "madam racecar madam" Output: true
Input: "abcbx" Output: false
The core challenge is to check if the string reads the same backward as forward. This problem 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:
This approach ensures that we only traverse the string once, achieving O(n) time complexity, and we use only a few extra variables, achieving O(1) space complexity.
Here is a step-by-step breakdown of the algorithm:
i
at the start (0) and j
at the end (n-1) of the string.i
is less than j
:
s[i]
is not equal to 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} - Returns true if the string is a palindrome, otherwise false.
*/
function isPalindrome(s) {
// Initialize two pointers
let i = 0;
let j = s.length - 1;
// Loop until the pointers meet in the middle
while (i < j) {
// If characters at the pointers do not match, return false
if (s[i] !== s[j]) {
return false;
}
// Move the pointers towards the center
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
Time Complexity: O(n), where n is the length of the string. We traverse the string once.
Space Complexity: O(1), as we use only a few extra variables.
Consider the following edge cases:
Input: "" Output: true
Input: "a" Output: true
To test the solution comprehensively, consider a variety of test cases:
Use testing frameworks like Jest or Mocha for automated testing.
When approaching such problems:
In this blog post, we discussed how to determine if a string is a palindrome using a two-pointer technique. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for improving algorithmic thinking and coding skills.
For further reading and practice: