Function to find out palindrome strings JavaScript

In this problem statement, our aim is to create a function to find out that the given string is palindrome with the help of Javascript functionalities. So for solving this problem first we need to understand the problem in simple terms.

Understanding the Problem Statement

We have given a string as an input string and our main aim is to check if the string is a palindrome string or not. If it is palindrome then return true otherwise return false.

What is a Palindrome?

A palindrome is a string that reads the same forwards and backwards. For example, "MADAM" is a palindrome because when reversed it remains "MADAM". Other examples include "racecar", "level", and "A man a plan a canal Panama" (ignoring spaces and case).

Original String: MADAM Reversed String: MADAM Result: Palindrome!

Algorithm

Step 1 ? Declare a function called isPalindrome which takes a string argument.

Step 2 ? Convert the string to lowercase and remove non-alphanumeric characters for accurate comparison.

Step 3 ? Reverse the cleaned string using JavaScript's built-in methods.

Step 4 ? Compare the original cleaned string with its reverse.

Step 5 ? Return true if they match, false otherwise.

Example Implementation

function isPalindrome(str) {
   // Convert to lowercase and remove non-alphanumeric characters
   str = str.toLowerCase().replace(/[^a-z0-9]/g, '');
    
   // Reverse the string and compare with the original
   return str === str.split('').reverse().join('');
}

const str = "Level";
const str1 = "Hello Javascript";
const str2 = "Wow";

console.log(isPalindrome(str));
console.log(isPalindrome(str1));

// Alternative way to show the output
const result = isPalindrome(str2);

if(result == true){
   console.log(str2, "is palindrome");
} else {
   console.log(str2, "is not palindrome");
}
true
false
Wow is palindrome

Alternative Approach Using Two Pointers

function isPalindromeOptimized(str) {
   // Clean the string
   str = str.toLowerCase().replace(/[^a-z0-9]/g, '');
   
   let left = 0;
   let right = str.length - 1;
   
   while (left 

true
false

Complexity Analysis

Method Time Complexity Space Complexity
Reverse and Compare O(n) O(n)
Two Pointers O(n) O(1)

The time complexity is O(n) for both approaches where n is the length of the string. The first method requires O(n) extra space for the reversed string, while the two-pointer approach uses O(1) constant space.

Conclusion

Both functions effectively check for palindromes with O(n) time complexity. The reverse method is more readable, while the two-pointer approach is more memory-efficient for large strings.

Updated on: 2026-03-15T23:19:00+05:30

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements