1. Filter String and Reverse Compare
Intuition
Iterate through s. If a character is alphanumeric, convert to lowercase and append to string filtered. Check if filtered == reverse(filtered).
When to apply: Basic baseline comparison.
Algorithm
- Create string
filtered = "". - For
cins: - If
isAlphanumeric(c):filtered += toLowerCase(c). - Return
filtered == reverse(filtered).
Filtered Lowercase Copy & Reverse Comparison Trace
2 of 2 questions left todayObservation: Strip punctuation and spaces, converting letters to lowercase
Observation: Strip punctuation and spaces, converting letters to lowercase.
Decision: Filtered string is "amanaplanacanalpanama" (length 21).
Invariant: Removes irrelevant punctuation.
#include <iostream>#include <string>#include <cctype>#include <algorithm> class Solution {public: bool isPalindrome(std::string s) { std::string filtered = ""; for (char c : s) { if (isalnum(c)) { filtered += tolower(c); } } std::string rev = filtered; std::reverse(rev.begin(), rev.end()); return filtered == rev; }}; int main() { Solution sol; std::cout << (sol.isPalindrome("A man, a plan, a canal: Panama") ? "true" : "false") << std::endl; // true std::cout << (sol.isPalindrome("race a car") ? "true" : "false") << std::endl; // false return 0;}Time & Space Complexity
- Time complexity:
O(N)— Builds a filtered string of length up to N and reverses it. - Space complexity:
O(N) auxiliary space
Why Brute Force Doesn't Scale:
Two pointers converge in a single pass with immediate early exit on the first mismatch.
Zero extra memory allocations; strict O(1) space.