skip to Main Content

I want to find if a string contains a palindrome word. An example would be hellosannasmith contains a palindrome word and should return sannas, however givemefood should return none. I first tried it through 2 for loops then I started to think why not a while loop but before I begin going the while loop route I want to see if it can be done in 2 for loops first.

I managed to get san into the new palindrome string variable but I’m not sure what else I am missing or overlooking here. Any help would be greatly appreciated.

function SearchingChallenge(str) {
  var palindromeStr = "";

  for (var i = 0; i < str.length / 2; i++) {
    for (var j = str.length - 1; str.length / 2 < j; j--) {
      if (str[i + 1] == str[j - 1] && str[i] == str[j]) {
        palindromeStr += str[i];
      }
    }
  }

  if (palindromeStr == "") {
    return "none";
  }

  return palindromeStr;
}

console.log(SearchingChallenge('hellosannasmith'));
console.log(SearchingChallenge('givemefood'));

3

Answers


    • You can define a Set() including all the words and then use dynamic programming to find the longest palindrome.

    • You can also add some conditions to return a palindrome, once found in the set. (It’s unclear from the question).

    const words = new Set(["hello", "sannas", "smith", "give", "me", "food"]);
    
    function SearchingChallenge(str) {
      const n = str.length;
      if (n === 0) return "none";
    
      let res = "";
      const dp = Array.from({ length: n }, () => Array(n).fill(false));
    
      for (let len = 1; len <= n; len++) {
        for (let i = 0; i <= n - len; i++) {
          const j = i + len - 1;
          if (len === 1) {
            dp[i][j] = true;
          } else if (len === 2) {
            dp[i][j] = str[i] === str[j];
          } else {
            dp[i][j] = str[i] === str[j] && dp[i + 1][j - 1];
          }
          if (dp[i][j] && len > res.length) {
            res = str.slice(i, j + 1);
          }
        }
      }
    
      return words.has(res) ? res : "none";
    }
    
    console.log(SearchingChallenge("hellosannasmith"));
    console.log(SearchingChallenge("givemefood"));

    Note:

    • This function has to be modified, to fulfill the requirements of the challenge.
    Login or Signup to reply.
  1. Something to consider is that your outer loop is only looking at the first half of the string and the inner loop is only looking at the second half of the string, meaning you are not checking for all possible substrings. Your approach is only considering whether one exists at the center of the string.

    Another note is that your condition if(str[i + 1] == str[j - 1] && str[i] == str[j]) is only checking pairs of characters at a specified position. So you are doing a partial character check, not an entire substring. So you end up building your string when two pairs match, which does not guarantee it’s a palindrome.

    Try making it more readable and robust by adjusting your loops:

      for (let i = 0; i < str.length; i++) {
        for (let j = i + 1; j <= str.length; j++) {
    

    Then you can build your substring using those indices

    Login or Signup to reply.
  2. First, by comparing str[i] = str[j] you can come to "polindrom" without having a polindrom. imaging "abcdefcba": for i=1,2,3, j=n-1,n-2,n-3 str[i] === str[j]. however they not connected, because in between you have other stuff.

    Secondly, in the same check you checking both str[i]===str[j] and str[i+1]===str[j-1] means the last char answering the criteria will not be entering the result (apart when they meet at the center, like your first example)

    So what you have to do is to check for every given interval if a substring in the given interval is a polindrom.

    Check the below example:

    function isPolindrom(str) {
      return str === str.split('').reverse().join('');
    }
    
    function SearchingChallenge(str) {
    
      if(str.length <= 1) return 'none';
      
      for(let i=0;i<str.length-3;i++) {
        for(let j=str.length-1; j>i+2; j--) {
            
            const substr = str.substring(i, j);
            if(isPolindrom(substr)) return substr;
        }
      }
    
      return 'none';
    }
    
    console.log(SearchingChallenge('hellosannasmith'));
    console.log(SearchingChallenge('givemefood'));
    console.log(SearchingChallenge('abcdef'));
    console.log(SearchingChallenge('someawesomeemosik'));

    Lastly, remeber two things:

    1. There can be more then one polindrom in the string. so you have to decide weather you return the first instance, or you return array of all found polyndroms. (in the example above i returning first found)
    2. You should define minimum chars of the accepted polindrom. Probably 1char you dont wanna consider polindrom. how about 2? "aa" is a polyndrom? and 3? in your second example, givemefood, eme is a polyndrom then. in above example min polyndrom length set ton three. but it need to be defined
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search