DEV Community

KenjiGoh
KenjiGoh

Posted on

Palindrome Revision

METHOD 1: Using built-in Reverse

Most straightforward but most inefficient, worst-case minimally a O(n) or O(n+k) linear time.

const isPalindrome = (str) => {
  return str === [...str].reverse().join("");
};
Enter fullscreen mode Exit fullscreen mode

METHOD 2: Using Decrementing For Loop

Not efficient as well, O(n) linear time

const isPalindrome = (str) => {
  let newStr = "";
  for (let i = str.length - 1; i >= 0; i--) {
    newStr += str[i];
  }
  return str === newStr;
};
Enter fullscreen mode Exit fullscreen mode

METHOD 3: Using Recursion

We can check the front and back of the str recursively from outer to inner elements.

const isPalindromeRec = (str) => {
  const sLen = str.length;
  if (sLen === 0 || sLen === 1) return true;
  // check front & back recursively
  if (str[0] === str[sLen - 1]) {
    return isPalindromeRec(str.slice(1, sLen - 1));
  }
  return false;
};
Enter fullscreen mode Exit fullscreen mode

METHOD 4: Using Loop to compare

Will be approximately twice more efficient than method 1 and 2, as we are only checking half the length.

const isPalindrome = (str) => {
  const sLen = str.length;
  for (let i = 0; i < sLen / 2; i++) {
    if (str[i] !== str[sLen - 1 - i]) {
      return false;
    }
  }
  return true;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)