Skip to lesson

Palindromes with two pointers

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)

PalindromeBrute.javaJava
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(" , : ! "));    }}
Output
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)

ValidPalindromeDemo.javaJava
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(" , : ! "));    }}
Output
Panama:   true
race a car: false
Symbols:  true

What this code does

  • On " , : ! ", the inner while (left < right && ...) loop stops as soon as left == right, and the characters at left == right are equal to themselves, returning true without going out of bounds.
  • No intermediate filtered or reversed String is 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 < right so a string of only symbols (" , ! ") never throws StringIndexOutOfBoundsException.
  • 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):

  1. Advance left while left < right and !Character.isLetterOrDigit(s.charAt(left)).
  2. Retreat right while left < right and !Character.isLetterOrDigit(s.charAt(right)).
  3. Compare Character.toLowerCase(s.charAt(left)) with Character.toLowerCase(s.charAt(right)). If they differ, return false; otherwise increment left++ and decrement right--.

Predict the output

Two pointers on a word

Work out the printed result.

What does this code print?

String s = "abca";
int left = 0, right = s.length() - 1;
while (left < right && s.charAt(left) == s.charAt(right)) {
left++;
right--;
}
System.out.println(left + " " + right);

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.

  1. Walk left and right inward while s.charAt(left) == s.charAt(right).
  2. If the loop finishes without a mismatch, return true (0 deletions needed).
  3. On the first mismatch at (left, right), return isPalindromeRange(s, left + 1, right) || isPalindromeRange(s, left, right - 1).

Example 3 · Valid Palindrome II: palindrome after deleting at most one character

ValidPalindromeIIDemo.javaJava
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"));    }}
Output
aba:  true
abca: true
abc:  false
deeee: true

What this code does

  • On "abca", left = 0 ('a') and right = 3 ('a') match. At left = 1 ('b') and right = 2 ('c'), they mismatch, and isPalindromeRange("abca", 2, 2) (skipping 'b') returns true.
  • Why can't we just greedily pick left + 1 if s.charAt(left + 1) == s.charAt(right)? Because in a string like "aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga" (or simply "ebcbbececabbacecbbcbe"), both s.charAt(left + 1) == s.charAt(right) and s.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 substring s[left + 1 .. right] is a strict palindrome, OR
  • Delete s.charAt(right) and check if the remaining substring s[left .. right - 1] is a strict palindrome. Because the helper isPalindromeRange(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

ReverseVowelsDemo.javaJava
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"));    }}
Output
IceCreAm -> AceCreIm
leetcode -> leotcede

What this code does

  • In "IceCreAm", the vowels in order are I, e, e, A. Reversing them yields A, e, e, I, producing "AceCreIm" while all consonants stay at their original indices.
  • Each character is inspected at most once by left or right, so the loop runs in O(n) time.

In while (left < right):

  • Advance left while left < right && !isVowel(chars[left]).
  • Retreat right while left < right && !isVowel(chars[right]).
  • Swap chars[left] and chars[right], then move both pointers (left++; right--;).
Remember to check both lowercase and uppercase vowels (a, e, i, o, u, A, E, I, O, U) in isVowel(char c)!

Next step

Check your understanding

10 quick questions