DEV Community

Abhi Raj
Abhi Raj

Posted on

check if string is palindrome using recursion in javascript

using one two pointer

let s = "madam";

let reverseArray = (s, left, right) => {
  if (left >= right) {
    console.log("it's palindrome");
    return true;
  }

  if (s[left] == s[right]) {
    reverseArray(s, left + 1, right - 1);
  } else if (s[left] != s[right]) {
    console.log("it's not palindrome");
    return false;
  }
};

reverseArray(s, 0, s.length - 1);
Enter fullscreen mode Exit fullscreen mode

using one pointer

let s = "madam";

let reverseArray = (s, left) => {
  if (left >= s.length / 2) {
    console.log("it's palindrome");
    return true;
  }

  if (s[left] == s[s.length - left - 1]) {
    reverseArray(s, left + 1, s.length - left - 1);
  } else if (s[left] != s[s.length - left - 1]) {
    console.log("it's not palindrome");
    return false;
  }
};

reverseArray(s, 0);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)