Two Pointer · Easy
Valid Palindrome Ignoring Punctuation
Solve it on DeVert Campus - free code runner
Problem
You are given a string s that may contain letters, digits, spaces, and punctuation. Using two pointers moving inward from both ends, determine whether s is a palindrome when only alphanumeric characters are considered and letter case is ignored (every other character is skipped entirely).
Input and output
Input: A single line containing the string s (it may contain spaces, so read the entire line as-is).
Output: Print "YES" if s is a palindrome under the stated rules, otherwise print "NO".
Example
Input: A man, a plan, a canal: Panama Output: YES
Constraints
1 <= |s| <= 10^5
s consists of printable ASCII characters (letters, digits, spaces, and punctuation)
Key observation
This is the two-pointer technique applied with an extra 'skip irrelevant characters' twist on top of the standard inward-comparison palindrome check - recognizing that the CORE technique (compare ends, move inward) stays the same, with just an added filtering step, keeps this from feeling like a brand new problem.
Intuition
Check whether a string is a palindrome when only letters and digits are considered, ignoring case, spaces, and punctuation.
Brute force: First build a cleaned string (stripping punctuation, lowercasing everything) into a NEW string, then check if that cleaned string is a palindrome using two pointers - this works but uses O(n) extra space for the cleaned copy, when skipping characters on the fly needs none.
Optimised: Skipping non-alphanumeric characters DIRECTLY within the two-pointer scan (rather than pre-building a cleaned copy) achieves the same correctness check with O(1) extra space - each pointer simply advances past irrelevant characters before every comparison, with no separate cleaning pass needed.
Step by step
1. Use two pointers starting at the BEGINNING and END of the string, moving toward the center.
2. At each step, SKIP over any character that is NOT a letter or digit before comparing.
3. Compare the two characters CASE-INSENSITIVELY; if they ever differ, stop immediately and answer No.
Complexity
Time: O(n) - both pointers together traverse the string once.
Space: O(1) - no cleaned copy of the string is ever built.
Edge cases
Handle a string made entirely of non-alphanumeric characters (there is nothing to compare, so it counts as a palindrome - print YES) and the maximum input length for an O(n) two-pointer scan.
Interview tip
Be ready to mention the O(n) extra space alternative (building a cleaned string first) as simpler to write but less space-efficient - demonstrating both options, and explaining why the pointer-skipping approach is preferred, is a good signal.