hi, let Avik connect you.


** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.

** You can check all the posts on the Posts page.

** More about me in the About Me section.

Valid Palindrome


  • Approach:

    1. Declare two pointers left and right.

    2. left assigned as 0 and right assigned as (|S| - 1), where, |S| = length of string.

    3. The left pointer will move forward and the right pointer will move backward.

    4. Compare each leftᵗʰ and rightᵗʰ character.

    5. If not matched, then return false.

    6. Return true after checking all the characters.


  • Time and Space Complexity:

      • Time Complexity: O(N)

      • Space Complexity: O(N)


Code [C++]

class Solution {

public:

bool isPalindrome(string s) {

int left = 0, right = s.size() - 1;

while(left < right){

if(!isalnum(s[left])) left++;

else if(!isalnum(s[right])) right--;

else if(tolower(s[left]) == tolower(s[right])){

left++; right--;

}

else return false;

}

return true;

}

};