2

My code works in console but gives the wrong result in hackerank Problem: Print count of all substrings that are palindromes from a string

function isPalindrome(str) {

  var len = str.length;
  var mid = Math.floor(len / 2);

  for (var i = 0; i < mid; i++) {
    if (str[i] !== str[len - 1 - i]) {
      return false;
    }
  }
  //Had to use this lengthy function because in
  //str == str.split('').reverse().join('');
  //I was getting error that split is not a function
  return true;
}

function scatterPalindrome(str) {
  var result = [],
    c = 0;

  for (let i = 0; i < str.length; i++) {
    for (let j = i + 1; j < str.length + 1; j++) {
      result.push(str.slice(i, j));
    }
  }
  for (let i = 0; i < result.length; i++) {
    let k = result[i];
    if (isPalindrome(k))
      c++;
  }
  return c; // the answer was always 1
}
console.log(scatterPalindrome("abc"));

input: "abc"

expected output: 3

actual output:1

Trobol
  • 1,210
  • 9
  • 12
GeekInTraining
  • 135
  • 1
  • 1
  • 5

1 Answers1

1

As I can't comment, so answering here, I will say you should check if they have mentioned there are many test cases, and in each test case you have to do the query then this is reasonable that your output and their output will not match

    take no.of testcases input
    while(testcases counter doesn't reach 0 )
           take string input
           call your function for answer for input and print
           decrement testcases counter
mss
  • 1,423
  • 2
  • 9
  • 18