
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a String Can be Made Palindrome in JavaScript
Exploring the realm of string manipulation in JavaScript reveals a fascinating challenge: determining whether a given string can be transformed into a palindrome. Palindromes, words or phrases that read the same forwards and backwards, possess an inherent allure and pique the curiosity of developers seeking to unravel their mystical properties. In this article, we embark on an enlightening journey to unravel the intricacies of checking if a string can be made into a palindrome using the powerful language features and algorithms inherent to JavaScript. By delving into the depths of string manipulation and employing innovative techniques, we unravel the enigma of transforming strings into palindromic wonders, thereby sharpening our skills as discerning JavaScript practitioners.
Problem Statement
The task at hand is to develop a JavaScript algorithm that can efficiently determine if a given string can be transformed into a palindrome by removing only one character. A palindrome remains the same when read forwards or backwards. The algorithm needs to thoroughly analyze the input string, examining its individual characters while considering the option of removing a single character if needed to create a palindrome. The output will be a Boolean value indicating whether the string can be transformed into a palindrome. For better understanding, let's consider the following example.
Sample Input
"racecar"
Sample Output
true
denoting that the string can indeed be transformed into a palindrome by deleting a maximum of one character.
Approach
In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript ?
Two-Pointer
Recursion
Dynamic Programming
Method 1: Two Pointer
The common problem of checking if a string can be made a palindrome in JavaScript can be solved using the two pointers approach. This involves initializing two pointers, one at the beginning and the other at the end of the string, comparing the characters at these pointers, and moving them towards the center. To implement this, define a JavaScript function that takes a string as input and initializes the pointers and a modifications variable. Then, use a while loop to compare characters, incrementing modifications for mismatches, and moving the pointers accordingly. After the loop, check if modifications is less than or equal to 1 to determine if a palindrome can be formed. Finally, return a boolean value indicating the possibility of creating a palindrome from the string.
Example
The canBePalindrome function checks if a string can be made a palindrome by removing at most one character. It uses the two-pointer approach to iterate over the string and compare characters. If the characters are equal, both pointers move towards the center. If not, it checks if a character can be removed by comparing neighboring characters. If a character has already been removed, it returns false. If the loop completes without returning false, it returns true, indicating the string can be made a palindrome. The example usage at the bottom demonstrates the function.
function canBePalindrome(str) { let left = 0; let right = str.length - 1; let removed = false; while (left < right) { if (str[left] !== str[right]) { if (removed) { return false; // Already removed a character, can't remove more } // Try removing either the character at the left or right pointer if (str[left + 1] === str[right]) { left++; } else if (str[left] === str[right - 1]) { right--; } else { return false; // Unable to make the string a palindrome by removing one character } removed = true; } left++; right--; } return true; // The string can be made a palindrome by removing at most one character } // Example usage: console.log(canBePalindrome("racecar")); // true console.log(canBePalindrome("abccdba")); // true console.log(canBePalindrome("abccba")); // true console.log(canBePalindrome("abcdcba")); // true console.log(canBePalindrome("abcddba")); // false console.log(canBePalindrome("abcdefg")); // false
Output
The following is the console output ?
true true true true true false
Method 2: Recursion
To check if a string can be made a palindrome using recursion in JavaScript, define a function called canBePalindrome() that takes the input string. For the base case, return true if the length of the string is less than or equal to 1. Otherwise, compare the first and last characters and recursively call canBePalindrome() with the updated string by removing those characters if they are equal. Repeat this process until reaching the base case. If the first and last characters are ever unequal, return false. Finally, call canBePalindrome() with the input string, store the result, and proceed with further processing or display an appropriate message based on the outcome.
Example
In this code, the canFormPalindrome function takes a string as input and returns true if the string can be made a palindrome by removing at most one character, and false otherwise. The isPalindrome function is a helper function used to check if a substring is a palindrome.
function canFormPalindrome(str) { // Helper function to check if a substring is a palindrome function isPalindrome(left, right) { while (left < right) { if (str[left] !== str[right]) { return false; } left++; right--; } return true; } // Recursive function to check if the string can be made a palindrome function checkPalindrome(left, right) { if (left >= right) { return true; // Base case: single character or empty string } if (str[left] === str[right]) { return checkPalindrome(left + 1, right - 1); // Characters match, check inner substring } // Try removing either left or right character and check the remaining substring return isPalindrome(left + 1, right) || isPalindrome(left, right - 1); } // Call the recursive function starting from the endpoints of the string return checkPalindrome(0, str.length - 1); } // Example usage console.log(canFormPalindrome("abcba")); // true console.log(canFormPalindrome("abbca")); // true console.log(canFormPalindrome("abcd")); // false
Output
The following is the console output ?
true true false
Method 3: Dynamic Programming
To check if a string can be transformed into a palindrome using dynamic programming in JavaScript, define a function called canBePalindrome that takes a string as input. Create a dynamic programming table to store the subproblems' results. Iterate over the string from both ends using two pointers, comparing the characters at these positions. If they are the same, move the pointers accordingly. If they are different, check if the substring between the pointers has already been processed in the table. If not, recursively call the canBePalindrome function on the substring and store the result. Consider excluding characters from the left and right pointers, updating the table if either case returns true. After updating the table, return the value stored at the entry representing the entire string to determine if it can be rearranged into a palindrome. This approach efficiently solves the problem by leveraging dynamic programming and breaking it into subproblems.
Example
In this code, the canFormPalindrome function takes a string str as input and returns a boolean value indicating whether the string can be made a palindrome by removing at most one character. The function uses a dynamic programming table dp to store the intermediate results and checks all possible substrings of str. Finally, it returns true if the whole string can be made a palindrome, and false otherwise.
function canFormPalindrome(str) { const n = str.length; // Create a 2D dynamic programming table const dp = Array(n) .fill(false) .map(() => Array(n).fill(false)); // Initialize the diagonal to true for (let i = 0; i < n; i++) { dp[i][i] = true; } // Fill the table diagonally for (let len = 2; len <= n; len++) { for (let i = 0; i < n - len + 1; i++) { const j = i + len - 1; if (str[i] === str[j]) { // Characters at the current indices are equal dp[i][j] = dp[i + 1][j - 1]; } else { // Try removing either the character at index i or j dp[i][j] = dp[i + 1][j] || dp[i][j - 1]; } } } // Return true if the whole string can be made a palindrome by removing at most one character return dp[0][n - 1]; } // Example usage: const str = "abca"; const canBePalindrome = canFormPalindrome(str); console.log(canBePalindrome);
Output
The following is the console output ?
true
Conclusion
In conclusion, the process of ascertaining whether a string can be transformed into a palindrome using JavaScript is a multifaceted endeavor. By leveraging various string manipulation techniques and employing a systematic approach, one can efficaciously determine the feasibility of achieving palindromic symmetry. The meticulous evaluation of character frequencies, along with the utilization of uncommon string algorithms, can lead to fascinating insights and creative solutions. Engaging in this intellectual pursuit allows programmers to delve into the intricacies of language manipulation, resulting in a gratifying exploration of the linguistic realm. Ultimately, the capacity to discern palindrome potential within a string serves as a testament to the ingenuity and versatility of JavaScript as a programming language.