How to improve my code in this coding problem

I’m solving a coding problem which is called Longest Palindromic Substring.
In this coding problem there is three test cases:

Example:

Input: "banana"
Output: "anana"

Input: "million"
Output: "illi"

Input: "tracecars"
Output: "racecar"

My code so far:

const longestPalindrome = (str) => {
  let newStr = str;
  let length = newStr.length;

  for (let i = 0; i < length; i++) {
    let reverse = str
      .slice(i, str.length + -1)
      .split("")
      .reverse()
      .join("");
    str = str.slice(i, str.length + -1);
    if (str === reverse) {
      return str;
    }
  }
  return false;
};

console.log(longestPalindrome("banana"));
console.log(longestPalindrome("million"));
console.log(longestPalindrome("tracecars"));

And in the console I can see the following results:

"ana"

"illi"

"cec"

That is means I have passed only one test case. So what is my wrong? What should I do to improve my code?

The problem here is that the method you are using to identify the palindrome within your string doesn’t work. Removing characters and reversing strings will not do the job, unless you arrive at the right answer by chance, as you have with “illi”. You need a method that looks for symmetry in the string. This is probably best handled using regular expressions of the form /(.)(.)\2\1/g. This regex is looking for two characters followed by the same two characters in reverse. For example the sequence “anana” in banana.
As our two characters “an” and “na” are separated by an “a” in this example, our regex needs an extra character added to make it work. This is /(.)(.).\2\1/g where the dots are characters and the brackets form capture groups that make the result available to the other end of the regex. \1 is the first capture group, in this example containing"a", and \2 is the second group containing “n”.
The regex starts its comparison at the beginning of the string and progresses one character at a time looking for a match. If there are two palindromes of equal length within the string , it will indicate a match at the first one and stop.

You can have a look at an example here where the regex is created dynamically, starting with the full length of the string and reducing in length until it finds a match or no match. I have tried it on your three example string and it returns the correct answers.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.