DEV Community

Cover image for Check if the given string is a palindrome or not
chandra penugonda
chandra penugonda

Posted on • Edited on

Check if the given string is a palindrome or not

This problem was asked by Intuit.

Given a string of characters, Check if the given string is a palindrome or not. A palindrome is a word, phrase, or sequence that reads the same backward as forwards, e.g. "racecar" or nurses run.

Example
function palindromeCheck(str) {

}

let str = "race car";
console.log(palindromeCheck(str)); // false
Enter fullscreen mode Exit fullscreen mode

Solution

function palindromeCheck(str) {
   let left=0, right= str.length-1

   while(left<right){
    if(str[left] !== str[right]) return false
    left++
    right--
   }
   return true
}

let str = "nursesrun";
console.log(palindromeCheck(str)); // true
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Preprocess the string to simplify checking - lowercase and remove non-alphanumerics
  • Use two pointers starting at each end of the string
  • Move the pointers inward, comparing characters
  • If any character pair doesn't match, return false
  • If pointers meet in the middle, all characters match so return true

Top comments (0)