How to solve LeetCode problem #9 Palindrome

Javascript – Leetcode problem #9 Palindrome

In this problem, we need to create a message that evaluates if a given integer is a palindrome (reads the same way from left>right and right>left) and return true or false. Read the full problem on LeetCode.

Pattern – How to detect a palindrome

A palindrome is a string that reads the same from left to right or right to left, i.e. “Otto”, “121”. To detect whether a given string is a palindrome, we should therefor compare symbols at opposite positions in the string. If each pair equals, the string is a palindrome.

Example:
"Otto" => first and last symbol match O==o, second and second to last symbol match t==t
121 => first and last symbol match 1==2, middle symbol has no comparison partner  

This logic words whether the string has an even or uneven number of symbols. For uneven strings, like “121”, the middle symbol has no comparison partner and it doesn’t need to. Since it sits right in the middle, I don’t need to deal with this symbol at all. No matter what it is, the string can still be read the same from either left or right.

Solution

First, I need to deal with the input. The function needs to accept an integer, so I am first transforming it to a string. If the resulting string is just one symbol long, I can just return true as any one-symbol-string is always a palindrome.

Then I start a two pointer loop. The first pointer (p1) starts at the first symbol of our given string and the second pointer (p2) starts at the last symbol. Each time the letters at each pointer match, we can move the pointers towards the middle (p1++, p2–). The loop breaks when the pointers meets in the middle (I can return true), or if any pair does not match (I can return false).

Here’s the full code:

var isPalindrome = function(x) {
    x = x.toString();
    if(x.length === 1) return true;
    let p1 = 0;
    let p2 = x.length-1;
    while(p1<p2){
        if(x[p1]!=x[p2]){
            return false;
        }
        else{
            p1++
            p2--
        } 
    }
    return true;
};

This is how I solved Leetcode problem #9 Palindrome in Javascript. Read more Leetcode solutions.