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?

Two problems jump to mind

  1. You keep changing str

  2. You seem to be making unfounded assumptions about where the palendrome will end

Keep in mind that the palendrome can start and stop anywhere in your string.

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