You will find javascript program and solution at single place.

Saturday, 2 July 2022

JavaScript find valid palindrome or not | leet code question 125

Hello friends, 
 If you come here to check the solution of the following question. 

 JavaScript find valid palindrome or not

this question is asked in LeetCode as a valid palindrome(Question Number -125) and its difficulty is easy.


If you search on google mostly we get solutions in Java, Python, or C++. if we are lucky then only we get the solution in javascript for the leet code questions.

So let's first understand the question.

A phrase is a palindrome if it reads the same forward and backward after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters. Alphanumeric characters include letters and numbers.


Given a string s, return true if it is a palindrome, or false otherwise.


Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

 

Constraints:

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.

So the solution to the above question is.





/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function(s) {

    s = s.toLowerCase().replace(/[\W_]/g,""); 	// replace() method will replace all non alphanumeric to empty chars
    let left = 0;
    let right = s.length-1;
    while(left < right){
        if(s[left]!==s[right]){
            return false;
        }
        left++;
        right--;
        
    }
    return true;
    
};



Complexity of the solution is as follows:

Time Complexity: O(N)

Space Complexity: O(1)

No comments:

Post a Comment