🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward, ignoring spaces, punctuation, and capitalization. Checking whether a string is a palindrome is a common problem in programming and can be approached in various ways. This guide will walk you through different methods to determine if a given string is a palindrome using JavaScript.
Problem Statement
Create a JavaScript program that:
- Accepts a string input.
- Determines whether the string is a palindrome.
- Returns a boolean value (
trueorfalse) indicating the result.
Example:
Input:
"radar"Output:
trueInput:
"hello"Output:
false
Solution Steps
- Read the Input String: Accept the string input from the user or define it directly in the program.
- Normalize the String: Convert the string to a consistent case (e.g., all lowercase) and remove non-alphanumeric characters to ensure accurate comparison.
- Check for Palindrome: Implement different methods—using built-in functions, iterative comparison, and recursive checking—to determine if the string is a palindrome.
- Display the Result: Output the boolean result (
trueorfalse) for each method.
Method 1: Using Built-in Functions
// JavaScript Program to Check if a String is Palindrome Using Built-in Functions
// Author: https://www.javaguides.net/
function isPalindromeBuiltIn(str) {
// Step 1: Normalize the string
const normalizedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
// Step 2: Reverse the string
const reversedStr = normalizedStr.split('').reverse().join('');
// Step 3: Compare the original and reversed strings
return normalizedStr === reversedStr;
}
// Example input
let inputString = "Radar";
let result = isPalindromeBuiltIn(inputString);
console.log(`Is "${inputString}" a palindrome? ${result}`);
Output:
Is "Radar" a palindrome? true
Explanation:
- Normalization: Converts the string to lowercase and removes any non-alphanumeric characters to ensure a fair comparison.
- Reversing: Splits the string into an array of characters, reverses the array, and joins it back into a string.
- Comparison: Checks if the normalized string is equal to its reversed version.
Method 2: Iterative Approach
// JavaScript Program to Check if a String is Palindrome Using Iteration
// Author: https://www.javaguides.net/
function isPalindromeIterative(str) {
// Step 1: Normalize the string
const normalizedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
// Step 2: Initialize pointers
let left = 0;
let right = normalizedStr.length - 1;
// Step 3: Compare characters from both ends
while (left < right) {
if (normalizedStr[left] !== normalizedStr[right]) {
return false;
}
left++;
right--;
}
return true;
}
// Example input
result = isPalindromeIterative(inputString);
console.log(`Is "${inputString}" a palindrome? ${result}`);
Output:
Is "Radar" a palindrome? true
Explanation:
- Normalization: Similar to the first method, it ensures the string is in a consistent format.
- Pointers: Uses two pointers, one starting at the beginning (
left) and the other at the end (right) of the string. - Comparison: Iteratively compares characters from both ends moving towards the center. If any pair of characters doesn't match, it returns
false. If all pairs match, it returnstrue.
Method 3: Recursive Approach
// JavaScript Program to Check if a String is Palindrome Using Recursion
// Author: https://www.javaguides.net/
function isPalindromeRecursive(str) {
// Step 1: Normalize the string
const normalizedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
// Step 2: Define the recursive function
function checkPalindrome(left, right) {
if (left >= right) {
return true;
}
if (normalizedStr[left] !== normalizedStr[right]) {
return false;
}
return checkPalindrome(left + 1, right - 1);
}
// Step 3: Initiate the recursive check
return checkPalindrome(0, normalizedStr.length - 1);
}
// Example input
result = isPalindromeRecursive(inputString);
console.log(`Is "${inputString}" a palindrome? ${result}`);
Output:
Is "Radar" a palindrome? true
Explanation:
- Normalization: Ensures the string is in a consistent format for comparison.
- Recursive Function: Defines a helper function
checkPalindromethat takes two indices (leftandright). It compares the characters at these indices and recursively moves towards the center. - Base Cases: If
leftis greater than or equal toright, it means all characters have been successfully compared. If any pair doesn't match, it returnsfalse.
Conclusion
This JavaScript program demonstrates three methods to check whether a string is a palindrome:
- Built-in Functions: Utilizes JavaScript's string and array methods to reverse the string and compare it with the original.
- Iterative Approach: Uses a two-pointer technique to compare characters from both ends of the string moving towards the center.
- Recursive Approach: Implements a recursive function to compare characters at corresponding positions from the start and end.
Each method has its advantages:
- Built-in Functions are concise and easy to implement but may not be the most efficient for very long strings.
- Iterative Approach is efficient and avoids the overhead of recursive calls.
- Recursive Approach offers a clear and elegant solution but can lead to stack overflow issues with very long strings due to deep recursion.
Choose the method that best fits your specific use case and performance requirements.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment