DEV Community

Vishal Gupta
Vishal Gupta

Posted on

Palindrome String in Javascript

This is a classical problem asked in mostly all the interviews.
I am posting the solution in Javascript, you can convert it in the language of your own choice.

Algo:

  1. Use two pointers (left & right)
  2. Put left at the start of string and right at the end of string
  3. Check the value at pointer and take decision on the basis of equality
  4. Move the pointers towards each other
  5. Until left is smaller than equal to right

Code:


 const isPalindrome  = function(A){
    A = A.replace(/[^0-9a-zA-Z]/g, "");
    A = A.toLowerCase();
    var left = 0
    var right = A.length; - 1;
    while(left <= right) {
        if(A[left] !== A[right]) {
            return 0
        }
        left++;
        right--;
    }
    return 1;
}

Note: In the above solution I have omitted the special characters and spaces.

Feel free to post suggestions or more efficient code

Top comments (4)

Collapse
 
neradev profile image
Moritz Schramm

I think this is way easier:

const isPalindrome = (s) => s.split('').reverse().join('') === s;
Collapse
 
provish profile image
Vishal Gupta

Sure, it is less code, but each function split, reverse, join will be executing a traversal, which will be 3 loops.

While it can be achieved in a single loop.

Collapse
 
thecodeboy_ravi profile image
Ravi Dhiman

Is there a way to find longest palindrome string from a given string?

Collapse
 
provish profile image
Vishal Gupta

Yes you can do that, make sliding window, on the string and increase the window until the the palindrome function returns false.

It is same like finding a sub array with maximum sum.

Google for Sliding window algos.