DEV Community

KenjiGoh
KenjiGoh

Posted on

3 1

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay