Search code examples
javascriptpalindrome

Break out of a while loop to find a Palindrome


This code does not work!

It causes the browser to crash;

Can someone please help me debug this? Not sure what is wrong.

My assumption is I have a pointer at the beginning of the string and the end of the string, And I check if each character is the same, and finish once the end and beginning pointer get to the middle...

But like I said it's not working.

function isPalindrome(string) {
  let isStringPalindrome = true;
  let left = 0;
  let right = string.length - 1;

  let middle = Math.floor((left + right)/2);

  while(string[left] === string[right]){
    left + 1;
    right - 1;
    if (left === middle && right === middle) {
      break;  
    }
    if (string[left] !== string[right]) {
      isStringPalindrome = false;
      break; 
    }
  }
    return isStringPalindrome;
}

Solution

  • Well, the two pointers idea is a good way to check palindrome. But in your code, you don't update the value of left and right. And if the string has even characters, the condition left === middle && right === middle will never be true.

    We can slightly change your code:

    function isPalindrome(string) {
      let left = 0;
      let right = string.length - 1;
    
      while(left < right){
        if (string[left] !== string[right]) {
          return false;
        }
        left += 1;
        right -= 1;
      }
      
      return true;
    }
    
    console.log(isPalindrome("abba"));
    console.log(isPalindrome("aba"));
    console.log(isPalindrome("abc"));
    console.log(isPalindrome("a"));