Palindromes with two pointers
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Cleaning a string with regular expressions and reversing a copy with StringBuilder.reverse() allocates two extra O(n) strings on the heap. Converging two pointers let you skip non-alphanumeric characters, allow a single deletion, or swap only vowels directly in O(n) time and O(1) extra space.
Valid palindrome ignoring symbols
A string is a valid palindrome if, after converting uppercase letters to lowercase and ignoring all non-alphanumeric characters (spaces, commas, colons), it reads the same forward and backward — for example, "A man, a plan, a canal: Panama".
Example 1 · Brute force: build a clean copy and compare it with its reverse (O(n) time, O(n) space)
public class PalindromeBrute { public static boolean isPalindrome(String s) { StringBuilder clean = new StringBuilder(); for (char c : s.toCharArray()) { if (Character.isLetterOrDigit(c)) { clean.append(Character.toLowerCase(c)); } } String forward = clean.toString(); String backward = clean.reverse().toString(); return forward.equals(backward); }
public static void main(String[] args) { System.out.println("Panama: " + isPalindrome("A man, a plan, a canal: Panama")); System.out.println("race a car: " + isPalindrome("race a car")); System.out.println("Symbols: " + isPalindrome(" , : ! ")); }}Panama: true race a car: false Symbols: true
What this code does
- The code keeps only letters and digits in lower case, reverses that copy and compares the two strings. It is easy to read and runs in O(n) time.
- The price is memory: two extra strings of up to n characters. Two pointers can compare the original string in place and use O(1) extra space.
Example 2 · Optimal: two pointers skip symbols in place (O(n) time, O(1) space)
public class ValidPalindromeDemo { public static boolean isPalindrome(String s) { int left = 0; int right = s.length() - 1; while (left < right) { while (left < right && !Character.isLetterOrDigit(s.charAt(left))) { left++; } while (left < right && !Character.isLetterOrDigit(s.charAt(right))) { right--; } if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { return false; } left++; right--; } return true; }
public static void main(String[] args) { System.out.println("Panama: " + isPalindrome("A man, a plan, a canal: Panama")); System.out.println("race a car: " + isPalindrome("race a car")); System.out.println("Symbols: " + isPalindrome(" , : ! ")); }}Panama: true race a car: false Symbols: true
What this code does
- On
" , : ! ", the innerwhile (left < right && ...)loop stops as soon asleft == right, and the characters atleft == rightare equal to themselves, returningtruewithout going out of bounds. - No intermediate filtered or reversed
Stringis allocated on the heap. - Why it is better: the same O(n) time, but no copy is built. The pointers read the original string and jump over symbols.
- Always guard inner skip loops with
left < rightso a string of only symbols (" , ! ") never throwsStringIndexOutOfBoundsException. Character.isLetterOrDigit(ch)handles both ASCII letters'a'-'z','A'-'Z'and digits'0'-'9'.- Time and Space: O(n) time and O(1) auxiliary space.
Instead of building a filtered string, place left = 0 and right = s.length() - 1. In each iteration of while (left < right):
- Advance
leftwhileleft < rightand!Character.isLetterOrDigit(s.charAt(left)). - Retreat
rightwhileleft < rightand!Character.isLetterOrDigit(s.charAt(right)). - Compare
Character.toLowerCase(s.charAt(left))withCharacter.toLowerCase(s.charAt(right)). If they differ, returnfalse; otherwise incrementleft++and decrementright--.
Predict the output
Two pointers on a word
Work out the printed result.
What does this code print?
Palindrome after deleting at most one character
What if you are allowed to delete at most one character to make the string a palindrome (Valid Palindrome II)? Brute force deletes each of the n characters one by one and checks the remaining string in O(n²) time.
- Walk
leftandrightinward whiles.charAt(left) == s.charAt(right). - If the loop finishes without a mismatch, return
true(0 deletions needed). - On the first mismatch at
(left, right), returnisPalindromeRange(s, left + 1, right) || isPalindromeRange(s, left, right - 1).
Example 3 · Valid Palindrome II: palindrome after deleting at most one character
public class ValidPalindromeIIDemo { private static boolean isPalindromeRange(String s, int left, int right) { while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true; }
public static boolean validPalindromeOneDelete(String s) { int left = 0; int right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return isPalindromeRange(s, left + 1, right) || isPalindromeRange(s, left, right - 1); } left++; right--; } return true; }
public static void main(String[] args) { System.out.println("aba: " + validPalindromeOneDelete("aba")); System.out.println("abca: " + validPalindromeOneDelete("abca")); System.out.println("abc: " + validPalindromeOneDelete("abc")); System.out.println("deeee: " + validPalindromeOneDelete("deeee")); }}aba: true abca: true abc: false deeee: true
What this code does
- On
"abca",left = 0 ('a')andright = 3 ('a')match. Atleft = 1 ('b')andright = 2 ('c'), they mismatch, andisPalindromeRange("abca", 2, 2)(skipping'b') returnstrue. - Why can't we just greedily pick
left + 1ifs.charAt(left + 1) == s.charAt(right)? Because in a string like"aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga"(or simply"ebcbbececabbacecbbcbe"), boths.charAt(left + 1) == s.charAt(right)ands.charAt(left) == s.charAt(right - 1)can be true at the mismatch, yet only one of the two branches is a full palindrome! Checking both branches with||is both simpler and bug-free.
With two pointers, walk left = 0 and right = s.length() - 1 inward as long as s.charAt(left) == s.charAt(right). All matched outer pairs are already symmetric and never need to be touched! If you hit the first mismatch at (left, right), you have only two possible fixes using your one deletion:
- Delete
s.charAt(left)and check if the remaining substrings[left + 1 .. right]is a strict palindrome, OR - Delete
s.charAt(right)and check if the remaining substrings[left .. right - 1]is a strict palindrome. Because the helperisPalindromeRange(s, i, j)runs at most twice on the remaining inner range, the entire algorithm still runs in O(n) time and O(1) space!
Reverse only the vowels
The exact same 'skip until target, then act' skeleton solves Reverse Vowels of a String and Reverse Only Letters. Convert s to char[] chars = s.toCharArray() (which takes O(n) space because Java String is immutable).
Example 4 · Reversing only the vowels of a string
public class ReverseVowelsDemo { private static boolean isVowel(char c) { return "aeiouAEIOU".indexOf(c) != -1; }
public static String reverseVowels(String s) { char[] chars = s.toCharArray(); int left = 0; int right = chars.length - 1; while (left < right) { while (left < right && !isVowel(chars[left])) { left++; } while (left < right && !isVowel(chars[right])) { right--; } char temp = chars[left]; chars[left] = chars[right]; chars[right] = temp; left++; right--; } return new String(chars); }
public static void main(String[] args) { System.out.println("IceCreAm -> " + reverseVowels("IceCreAm")); System.out.println("leetcode -> " + reverseVowels("leetcode")); }}IceCreAm -> AceCreIm leetcode -> leotcede
What this code does
- In
"IceCreAm", the vowels in order areI, e, e, A. Reversing them yieldsA, e, e, I, producing"AceCreIm"while all consonants stay at their original indices. - Each character is inspected at most once by
leftorright, so the loop runs in O(n) time.
In while (left < right):
- Advance
leftwhileleft < right && !isVowel(chars[left]). - Retreat
rightwhileleft < right && !isVowel(chars[right]). - Swap
chars[left]andchars[right], then move both pointers (left++; right--;).
a, e, i, o, u, A, E, I, O, U) in isVowel(char c)!Next step
Check your understanding
10 quick questions