Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading