Sign Up Free
Test1

test

โ€ขEasy
53w5

title: "Valid Palindrome" description: "Master the Two Pointer pattern with a clean, interview-ready solution." pattern: "Two Pointers" difficulty: "Easy" leetcode: 125 time: "O(n)" space: "O(1)"

๐Ÿง  Valid Palindrome

Pattern: Two Pointers
Difficulty: Easy
LeetCode: 125
Time: O(n) ยท Space: O(1)


๐ŸŽฏ Question Statement

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

Alphanumeric characters include letters (a-z, A-Z) and numbers (0-9).

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

Examples

| Input | Output | Explanation | |---|:---:|---| | "A man, a plan, a canal: Panama" | ๐ŸŸข true | Ignoring spaces and punctuation โ†’ amanaplanacanalpanama | | "race a car" | ๐Ÿ”ด false | Characters don't match from both ends | | " " | ๐ŸŸข true | No alphanumeric characters remain |

Constraints

  • 1 <= s.length <= 2 * 10โต
  • s consists only of printable ASCII characters.

๐Ÿ’ก How to Explain It in an Interview

If the interviewer asks:

"How would you solve this?"

You can say:

"I would use the Two Pointer pattern. One pointer starts from the left and another starts from the right. I skip any non-alphanumeric characters, compare the two valid characters case-insensitively, and then move both pointers toward the center. If any pair doesn't match, I immediately return false. If all pairs match, the string is a palindrome."


๐Ÿš€ Why Two Pointers?

We don't need to create another cleaned string.

Instead, we compare characters directly from the original string.

text
A man, a plan, a canal: Panama
 
โ†‘                                     โ†‘
L                               R
 
Skip invalid characters
 
 โ†“                       โ†“
 
 a                             a
 
 โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ COMPARE โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

This gives us:

  • โšก O(n) Time
  • ๐Ÿ’พ O(1) Extra Space

๐Ÿ” Step-by-Step Algorithm

01. Start from both ends

text
left  โ†’ 0
right โ†’ n - 1

02. Skip invalid characters

If the left character isn't alphanumeric:

text
left++

If the right character isn't alphanumeric:

text
right--

03. Compare valid characters

Compare both characters after converting them to lowercase.

text
lower(s[left]) == lower(s[right])

If they are different:

text
return false

04. Move both pointers

After a successful comparison:

text
left++
right--

05. Finish

If all characters match:

text
return true

๐Ÿงช Sample Test Case

Input

text
s = "0P"

Step 1 โ€” Start

text
0 P
โ†‘ โ†‘
L R

Both characters are alphanumeric.

Step 2 โ€” Convert to lowercase

text
'0' != 'p'

Step 3 โ€” Mismatch

text
๐Ÿ”ด return false

๐Ÿ’ป Solutions

๐ŸŸฆ C++

cpp
class Solution {
public:
    bool isPalindrome(string s) {
        int left = 0;
        int right = s.length() - 1;
 
        while (left <= right) {
 
            if (!isalnum(s[left])) {
                left++;
            }
            else if (!isalnum(s[right])) {
                right--;
            }
            else {
                if (tolower(s[left]) != tolower(s[right])) {
                    return false;
                }
 
                left++;
                right--;
            }
        }
 
        return true;
    }
};

๐ŸŸช Java

java
class Solution {
    public boolean isPalindrome(String s) {
        int start = 0;
        int last = s.length() - 1;
 
        while (start <= last) {
            char currFirst = s.charAt(start);
            char currLast = s.charAt(last);
 
            if (!Character.isLetterOrDigit(currFirst)) {
                start++;
            }
            else if (!Character.isLetterOrDigit(currLast)) {
                last--;
            }
            else {
                if (Character.toLowerCase(currFirst) !=
                    Character.toLowerCase(currLast)) {
                    return false;
                }
 
                start++;
                last--;
            }
        }
 
        return true;
    }
}

๐ŸŸจ JavaScript

javascript
class Solution {
    isPalindrome(s) {
        let left = 0;
        let right = s.length - 1;
 
        const isAlphaNumeric = (ch) => {
            return /[a-zA-Z0-9]/.test(ch);
        };
 
        while (left <= right) {
            if (!isAlphaNumeric(s[left])) {
                left++;
            }
            else if (!isAlphaNumeric(s[right])) {
                right--;
            }
            else {
                if (
                    s[left].toLowerCase() !==
                    s[right].toLowerCase()
                ) {
                    return false;
                }
 
                left++;
                right--;
            }
        }
 
        return true;
    }
}

๐Ÿ Python

python
class Solution:
    def isPalindrome(self, s: str) -> bool:
        left = 0
        right = len(s) - 1
 
        while left <= right:
 
            if not s[left].isalnum():
                left += 1
 
            elif not s[right].isalnum():
                right -= 1
 
            else:
                if s[left].lower() != s[right].lower():
                    return False
 
                left += 1
                right -= 1
 
        return True

โฑ๏ธ Complexity Analysis

| Metric | Complexity | |---|:---:| | ๐Ÿ• Time | O(n) | | ๐Ÿ’พ Extra Space | O(1) |

Why O(n)?

Both pointers move only toward the center.

Each character is processed at most a constant number of times.

Why O(1) Space?

We don't create another string or array.

Only two pointers and a few variables are used.


๐Ÿงฉ Pattern to Remember

text
            TWO POINTERS
                  โ†“
        Start from both ends
                  โ†“
        Skip invalid characters
                  โ†“
          Compare characters
                  โ†“
        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
        โ†“                   โ†“
    Mismatch              Match
        โ†“                   โ†“
      false          Move inward
                            โ†“
                     Pointers cross
                            โ†“
                          true

โญ Interview Takeaway

When a problem asks you to compare elements from opposite ends of a sequence, think Two Pointers.

The key idea is:

text
LEFT  โ†’ โ†’ โ†’     โ† โ† โ†  RIGHT

Move inward until the pointers meet or a mismatch is found.