check whether a string is palindrome or not in javascript

To check whether a string is palindrome or not in javascript, we can use the following approach:

index.tsx
function isPalindrome(str) {
  const len = str.length;
  for (let i = 0; i < len / 2; i++) {
    if (str[i] !== str[len - 1 - i]) {
      return false;
    }
  }
  return true;
}
179 chars
10 lines

In this approach, we are essentially iterating through the string from both ends towards its center and checking if the characters at these positions are same or not.

For example, let's say we have a string "racecar". The length of the string is 7. We will start by comparing the first and last characters of the string ("r" and "r"). Since they are same, we move on to the next characters ("a" and "a"), and so on. Finally, we will end up with the middle character ("e"), which does not need to be compared with anything. If all the characters from both ends are same, we return true, otherwise we return false.

This approach has a time complexity of O(n/2), which is essentially O(n) and a space complexity of O(1).

We can optimize this solution further by using two pointers approach. Here is the optimized solution:

index.tsx
function isPalindrome(str) {
  let left = 0;
  let right = str.length - 1;
  while (left < right) {
    if (str[left] !== str[right]) {
      return false;
    }
    left++;
    right--;
  }
  return true;
}
208 chars
13 lines

In this approach, we are using two pointers to traverse the string from both ends. We keep moving the pointers towards each other until they cross each other. If at any point the characters at these positions are different, we return false, otherwise we return true.

This optimized approach has the same time complexity and space complexity as the previous approach.

gistlibby LogSnag