Valid Palindrome in Java: Solution, Explanation & Practice
Check if string is palindrome considering only alphanumeric
Problem summary
Given a string, determine if it's a palindrome considering only alphanumeric characters and ignoring case. Use two pointers from both ends.
Starter code
public class Main {
public static void main(String[] args) {
String s = "A man, a plan, a canal: Panama";
// Two pointers: left and right
// Skip non-alphanumeric characters
// Compare characters (case-insensitive)
// Print: Is palindrome: true
}
}Expected output and test cases
- A man, a plan, a canal: Panama
Is palindrome: true
- race a car
Is palindrome: false
-
Is palindrome: true
Hints
- Use Character.isLetterOrDigit() to check valid characters
- Use Character.toLowerCase() for case-insensitive comparison
- Move pointers inward, skipping invalid characters
- If characters don't match, it's not a palindrome
Validated solution
Reveal Java solution
public class Main {
static boolean validPalindrome(String text) {
int left = 0, right = text.length() - 1;
while (left < right) {
while (left < right && !Character.isLetterOrDigit(text.charAt(left))) left++;
while (left < right && !Character.isLetterOrDigit(text.charAt(right))) right--;
if (Character.toLowerCase(text.charAt(left)) != Character.toLowerCase(text.charAt(right))) return false;
left++; right--;
}
return true;
}
public static void main(String[] args) {
System.out.println("Is palindrome: " + validPalindrome("A man, a plan, a canal: Panama"));
}
}How to approach the problem
Use two pointers and skip characters outside the stated alphanumeric definition before comparing. This avoids allocating a cleaned copy while still applying the same normalization at both ends.
Approach
- Move inward past punctuation and spaces.
- Compare lowercased alphanumeric characters.
- Stop immediately on a mismatch.
Time and space complexity
Time: O(n). Space: O(1).
Edge cases to test
- A blank or punctuation-only string is valid under this definition.
- Character.isLetterOrDigit handles more than ASCII.
Common mistakes
- Removing only spaces but not other punctuation.
- Advancing a pointer after a mismatch instead of returning false.
Follow-up challenge
Make the scan code-point-aware for full Unicode text.
Related Data Structures & Algorithms exercises
- Practice Container With Most Water in Java
- Practice Three Sum in Java
- Practice Maximum Sum Subarray of Size K in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler