5

I am trying to find out whether a string is a palindrome by recursion using javascript. But I can't figure out what I am missing in the code.

var firstCharacter = function(str) {
    return str.slice(0, 1);
};

var lastCharacter = function(str) {
    return str.slice(-1);
};

var middleCharacters = function(str) {
    return str.slice(1, -1);
};

var isPalindrome = function(str) {
    if(str.length < 2) {
        return true;
    } else {
        if(firstCharacter(str) == lastCharacter(str)) {
            isPalindrome(middleCharacters(str));
        } else return false;
    }
};

var checkPalindrome = function(str) {
    console.log("Is this word a palindrome? " + str);
    console.log(isPalindrome(str));
};


checkPalindrome("a");
//Program.assertEqual(isPalindrome("a"), true);
checkPalindrome("matom");
//Program.assertEqual(isPalindrome("motor"), false);
checkPalindrome("rotor");
//Program.assertEqual(isPalindrome("rotor"), true);

For sure something is wrong with the recursive call. I would love to have your help. Thanks. I am attaching the output of my code.

enter image description here

Keyur Ramoliya
  • 1,900
  • 2
  • 16
  • 17
Niaz Ahsan
  • 351
  • 1
  • 7
  • 21

9 Answers9

11

Here is another recursive palindrome.

function checkPalindrome(str){
    if(str.length === 1) return true;
    if(str.length === 2) return str[0] === str[1];
    if(str[0] === str.slice(-1)) return checkPalindrome(str.slice(1,-1))
    return false;
}

console.log(checkPalindrome('a')) // true
console.log(checkPalindrome('matom')) // false
console.log(checkPalindrome('rotor')) // true
Avadhut Thorat
  • 997
  • 11
  • 7
5

You defined isPalindrome() to return a value, so if you call it yourself, recursively or otherwise, you need to deal with that return value. Also, your if ... else logic is too complicated, simplify:

var isPalindrome = function(str) {
    if (str.length < 2) {
        return true;
    }

    if (firstCharacter(str) == lastCharacter(str)) {
        return isPalindrome(middleCharacters(str));
    }

    return false;
};
cdlane
  • 40,441
  • 5
  • 32
  • 81
5
    const isPalindrome = str => {
    const strLen = str.length;
    if (strLen < 2) return true;

    if (str[0] === str[strLen - 1]) {
        return isPalindrome( str.slice(1, strLen - 1) );
    }

    return false;
};

console.log(isPalindrome('madam'));
Nitin .
  • 808
  • 9
  • 12
1

Using slice creates an array - if you want to compare the first and last char, you will need to extract the value from the array before applying == -

var firstCharacter = function(str) {
    return str.slice(0, 1)[0] // <-- get the first element of the slice
}

var lastCharacter = function(str) {
    return str.slice(-1)[0] // <-- get the first element of the slice
}

Here's another recursive solution that uses parameters l (left) and r (right) to check the string using indexes (rather than creating intermediate values with slice) -

const palindrome = (s = "", l = 0, r = s.length - 1) =>
  r - l < 2
    ? true
    : s[l] === s[r] && palindrome (s, l + 1, r - 1)

console.log
  ( palindrome ("motor")   // false
  , palindrome ("rotor")   // true
  , palindrome ("racecar") // true
  , palindrome ("wow")     // true
  , palindrome ("i")       // true
  )

And here's a mutually recursive definition. It's wasteful but it has an elegant form nonetheless -

const pal = ([ s, ...more ]) =>
  more.length === 0 || pal2 (more.reverse(), s)

const pal2 = ([ s, ...more ], q) =>
  s === q && pal (more.reverse())

console.log
  ( pal ("motor")   // false
  , pal ("rotor")   // true
  , pal ("racecar") // true
  , pal ("wow")     // true
  , pal ("i")       // true
  )
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • Correction: [`String.prototype.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) actually returns a String, so the `[0]` additions are not necessary (although harmless here.) – Scott Sauyet Nov 08 '21 at 16:42
0

Here is another way to recursively check for a palindrome in JS:

function isPalindrome(str){ if (str[0] === str[str.length - 1] && str.length > 1) { isPalindrome(str.substring(1, str.length -1)) return true }else{ return false } }

0

Here's a simple answer for ya. Basically we are comparing the first character to last character and acting accordingly.

const isPalindrome = str => {
  if (str.length <= 1) return true;
  if (str[0] !== str[str.length - 1]) return false;
  
  return isPalindrome(str.slice(1,-1))
}
ByteTheBits
  • 319
  • 1
  • 5
  • 13
0
const isPalindrome = str => {
    
    // base case
    if(str.length === 1) return true;
    if(str.length === 2) return str[0] === str[1];

    if(str[0] === str[str.length - 1]) {
        return isPalindrome(str.slice(1, -1))
    }

    return false;
}

you can use recursion

base case

we have a base case (the simple case) if the string is one char we simply returns true.

if it has two chars we check if the first char is identical to the second and we return true if they are.

recursive case

if it is more than two chars we check if the first and last chars are identical or not if they are not we simply return false

but if they are identical so we now want to do the same thing with other chars so we call the same function with the same string but removing the first and last chars because we already know that they are identical and we keep going until we reach the base case.

hope this be useful

some tests

isPalindrome('p')    // true
isPalindrome('po')   // false
isPalindrome('pp')   // true
isPalindrome('pop')  //true
  • Note that this will fail with an empty string. It would be fixed, and simplified, if you replaced your two base case guards with `if (str .length < 2) return true`. Also note that the function name is misspelled. – Scott Sauyet Nov 08 '21 at 16:49
0

What's about this solution ?

function isPalindrome(str){
  if (str.length > 3) return isPalindrome(str.substring(1, str.length-1));
  return str[0] === str[str.length-1];
}
Lasalle
  • 63
  • 7
0

My simple implementation for a recursive palindrome check, in 2022:

function isPalindrome(str) {
  if (!str.length || str.length === 1) return true;
  return str[0] === str.at(-1) ? isPalindrome(str.substr(1, str.length - 2)) : false;
}
console.log(isPalindrome('catotac'));

Iterations breakdown:

// 1st iteration:
isPalindrome('catotac');
//2nd iteration
isPalindrome('atota');
//3rd
isPalindrome('tot');
// 4th iteration
isPalindrome('o'); // true
elitu
  • 473
  • 1
  • 4
  • 8