Forming palindrome using at most one deletion in JavaScript


Problem

We are required to write a JavaScript function that takes in a string, str, as the first and the only argument.

Our function may delete at most one character from the string str and we are required to check whether we can make it a palindrome doing so.

For example, if the input to the function is

Input

const str = 'dr.awkward';

Output

const output = true;

Output Explanation

Because if we delete ‘.’ from the string,

Example

Following is the code −

 Live Demo

const str = 'dr.awkward';
const validPalindrome = (str = '') => {
   const valid = (left, right) => {
         for (let i = left; i <= Math.floor((left + right) / 2); i++) {
         if (str[i] !== str[right - (i - left)]) {
            return false
         }
      }
      return true
   }
   for (let i = 0; i <= Math.floor(str.length / 2); i++) {
      const right = str.length - 1 - i
      if (str[i] !== str[right]) {
         return valid(i, right - 1) || valid(i + 1, right)
      }
   }
   return true
}
console.log(validPalindrome(str));

Output

true

Updated on: 24-Apr-2021

121 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements