05. Palindrome Sentence
β GFG solution to the Palindrome Sentence problem: check if a string is palindromic after removing non-alphanumeric characters and converting to lowercase using two pointers technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
A palindrome sentence is a sequence of characters, such as word, phrase, or series of symbols that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumeric characters (including spaces and punctuation).
Your task is to determine if the given string s forms a palindrome sentence according to the above definition.
π Examples
Example 1
Input: s = "Too hot to hoot"
Output: true
Explanation: If we remove all non-alphanumeric characters and convert all uppercase letters to lowercase,
string s will become "toohottohoot" which is a palindrome.Example 2
Input: s = "Abc 012..## 10cbA"
Output: true
Explanation: If we remove all non-alphanumeric characters and convert all uppercase letters to lowercase,
string s will become "abc01210cba" which is a palindrome.Example 3
π Constraints
$1 \le s.length() \le 10^6$
β
My Approach
The optimal approach uses the Two Pointers technique to check palindrome properties without creating an additional string:
Two Pointers Technique
Initialize Pointers:
Use two pointers:
leftstarting from beginning andrightstarting from end.Move pointers towards each other while checking palindrome condition.
Skip Non-Alphanumeric:
When
leftpointer encounters non-alphanumeric character, increment it.When
rightpointer encounters non-alphanumeric character, decrement it.Continue until both pointers point to valid alphanumeric characters.
Compare Characters:
Convert both characters to lowercase using
tolower()function.If characters don't match, return
falseimmediately.If they match, move both pointers inward.
Continue Until Complete:
Repeat process until
left >= right.If all comparisons pass, return
true.
Edge Cases:
Empty string or single character is considered palindrome.
String with only non-alphanumeric characters is palindrome.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the length of the string. Each character is visited at most once by either the left or right pointer, making it a single pass algorithm.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for the two pointers and temporary variables, regardless of the input size.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated