Valid Palindrome

NikhithaNikhitha
3 min read

Author: Nikhitha
Category: C++ | Problem Solving | LeetCode
Topic: String Manipulation + Two Pointer Technique

πŸ” Problem Statement

Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

βœ… Example Inputs & Outputs

InputOutput
"A man, a plan, a canal: Panama"true
"race a car"false
""true

πŸ’‘ What Is a Palindrome?

A palindrome is a word or sentence that reads the same forwards and backwards, ignoring punctuation, spaces, and letter casing.

πŸ§ͺ Solution 1: Brute Force (Clean, Reversed Comparison)

βœ”οΈ Intuition:

  1. Filter the input string to remove all non-alphanumeric characters.

  2. Convert everything to lowercase for case-insensitive comparison.

  3. Reverse the filtered string.

  4. If the original filtered string equals the reversed one β†’ it’s a palindrome!

πŸ”— Code:

class Solution {
public:
    bool isPalindrome(string s) {
        int n = s.size();
        if(s == "")
            return true;

        string result = "";
        for (int i = 0; i < n; i++) {
            if (isalnum(s[i]))
                result += tolower(s[i]);
        }

        string reversal = result;
        reverse(reversal.begin(), reversal.end());

        return result == reversal;
    }
};

⏱️ Time & Space Complexity:

  • Time: O(n)

  • Space: O(n) β†’ for the result and reversal strings.

βš™οΈ Key Functions Used:

  • isalnum(c) – checks if character c is a letter or digit.

  • tolower(c) – converts character c to lowercase.

  • reverse(str.begin(), str.end()) – reverses the string.

πŸš€ Solution 2: Optimized – Two Pointer Technique

βœ”οΈ Intuition:

Let’s be memory-smart! Why create new strings when we can just compare characters from both ends?

  • Use two pointers: left at start, right at end.

  • Skip non-alphanumeric characters.

  • Convert both chars to lowercase and compare.

  • If all pairs match β†’ it’s a palindrome.

πŸ”— Code:

class Solution {
public:
    bool isPalindrome(string s) {
        int left = 0, right = s.length() - 1;

        while (left < right) {
            while (left < right && !isalnum(s[left])) left++;
            while (left < right && !isalnum(s[right])) right--;

            if (tolower(s[left]) != tolower(s[right]))
                return false;

            left++;
            right--;
        }

        return true;
    }
};

🧠 Key Concepts:

ConceptPurpose
Two PointersCompare characters from both ends
isalnum()Ignore spaces, punctuation, etc.
tolower()Make comparison case-insensitive
In-place logicSaves space by not creating new strings

⏱️ Time & Space Complexity:

  • Time: O(n)

  • Space: O(1) β†’ no extra strings, pure pointer logic!

πŸ“Œ Final Thoughts

FeatureBrute ForceOptimized (Two Pointers)
Simplicityβœ… Easy to understand🧠 Slightly more logic-heavy
Time ComplexityO(n)O(n)
Space ComplexityO(n)βœ… O(1)
Ideal ForLearning phase, quick demoProduction-level usage

If you're prepping for coding interviews or placements, go with the two pointer version β€” it's clean, memory-efficient, and shows you understand core algorithmic patterns.

πŸ§ͺ Test Cases to Try

Solution sol;
cout << sol.isPalindrome("race a car") << endl; // false
cout << sol.isPalindrome(" ") << endl;          // true
cout << sol.isPalindrome("0P") << endl;         // false
cout << sol.isPalindrome("madam") << endl;      // true

problem link: https://leetcode.com/problems/valid-palindrome/description/

0
Subscribe to my newsletter

Read articles from Nikhitha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nikhitha
Nikhitha

πŸš€ Software Developer | DSA Enthusiast | Problem Solver πŸ”Ή Sharing daily DSA solutions, coding insights, and interview prep πŸ”Ή Passionate about writing optimized & bug-free code