Revision 2·24 Sept
Valid Palindrome
tl;dr
Write a function that takes a string, s, as an input and determines whether or not it is a palindrome
full write-up
Write a function that takes a string, s, as an input and determines whether or not it is a palindrome
Check if a String Is a Palindrome
Note
A palindrome is a word, phrase, or sequence of characters that reads the same backward as forward.
Constraints
1 ≤ s.length ≤ 2 × 10⁵- The string
swill only have English uppercase letters, lowercase letters, digits, and spaces.
Examples
Example 1
Input: ABCBA
Output: TRUE
Example 2
Input: ABCCA
Output: FALSE
Solution
This is an easy problem to solve using the two pointer method.
- We create two pointers: one starting at the left end of the string, and one starting at the right end.
- We compare the characters at both pointers:
- If they are not the same, the string is not a palindrome. We return
falseright away. - If they match, we move the left pointer forward and the right pointer backward.
- If they are not the same, the string is not a palindrome. We return
- We keep doing this until the two pointers meet or cross. If we get through the whole string without finding a mismatch, the string is a palindrome. We return
true.
Code
function isPalindrome(s) {
let left = 0,
right = s.length - 1;
while (left < right) {
if (s[left] != s[right]) {
return false;
}
left++;
right--;
}
return true;
}
Complexity
- Time complexity: O(N)
- Space complexity: O(1)