3
\$\begingroup\$

I submitted my solution for palindrome Index coding challenge but I get "test cases terminated due to time out error". My code is working and so I don't know what else to do to optimize it. Please help:

function palindromeIndex(s) {
    let palindrome = s === s.split('').reverse().join('')
    if(!palindrome) {
        let i = 0
        let integerIndex = []
        let arr = s.split('')
        while(i < s.length) {
            arr.splice(i,1)
            if(arr.join('') === arr.reverse().join('')) {
               integerIndex.push(i) 
            }
            arr = s.split('')
            i++
        }
        return integerIndex.length > 0 ? integerIndex[0] : - 1
    }else {
        return -1
    }
}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Could you please add the text of the question and a link to the coding challenge to the body of this question? We need the exact specification of the coding challenge. \$\endgroup\$
    – pacmaninbw
    Commented May 30, 2020 at 17:54

1 Answer 1

2
\$\begingroup\$

It may well be an error @ Hackerrank. If I'm not mistaken the nodejs-code expects you to provide console input. Or you may have accidentally changed something in the surrounding code.

Concerning your code: writing ES20xx, it's good practice to terminate lines with a semicolon (;), because not doing so may result in nasty bugs.

let palindrome = s === s.split('').reverse().join('')

You don't need this variable. It could've been:

if(s !== s.split('').reverse().join('')) {

Furthermore, if you wanted to declare a variable, it could've been a const here (you are not modifying it afterwards).

Just for fun, here's an alternative approach, using substrings from the original given string:

"hannach,ava,reopaper,annana,ewve,blob,otto,michael,racecaar,wasitacatiwsaw"
  .split(",")
  .forEach(name => console.log(`[${name}] => ${palindromeIndex(name)}`));
  
function palindromeIndex(s) {
    if (`${[...s]}` === `${[...s].reverse()}`) { return "is palindrome"; }
    let i = 0;
    while(i < s.length) {
      const sx = `${i < 1 ? s.substr(1, 0) : s.substr(0, i)}${s.substr(i + 1)}`; 
      const  rsx = `${[...sx].reverse().join("")}`;
      if (sx === rsx) {
        return `removing '${s[i]}' (@ position ${i}): '${sx}'`;
      };
      i += 1;
    }
    return -1;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.