⚡ Play a quiz
HomeLearnData Structures & AlgorithmsStrings › Palindromes & anagrams
Lesson 2 of 3 · Strings

Palindrome and Anagram Problems in Strings

Strings67%

Two question shapes cover an outsized share of string interviews. Palindromes are a two-pointer problem; anagrams are a counting problem. Recognising which is which takes seconds, and both have a clean O(n) answer.

Read time
8 min
Track
Data Structures & Algorithms
Sections
3
Practice
5

Palindrome checks

Palindrome check ignoring case and punctuation
boolean isPalindrome(String s) {
    int left = 0, 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;
}

O(n) time, O(1) space, and no new string is allocated. Reversing the string and comparing also works and is fine to mention — but it costs O(n) extra space, so lead with the two-pointer version.

Longest palindromic substring: expand around centre

Every palindrome has a centre. There are 2n-1 of them — n single characters and n-1 gaps between characters — and from each you can expand outwards while the characters match.

Expand around every centre
String longestPalindrome(String s) {
    if (s.isEmpty()) return "";
    int start = 0, end = 0;

    for (int i = 0; i < s.length(); i++) {
        int odd  = expand(s, i, i);       // centre on a character
        int even = expand(s, i, i + 1);   // centre between characters
        int len  = Math.max(odd, even);
        if (len > end - start) {
            start = i - (len - 1) / 2;
            end   = i + len / 2;
        }
    }
    return s.substring(start, end + 1);
}

int expand(String s, int left, int right) {
    while (left >= 0 && right < s.length() &&
           s.charAt(left) == s.charAt(right)) {
        left--;
        right++;
    }
    return right - left - 1;              // length of the matched palindrome
}
Common mistake

Forgetting even-length centres

Only expanding from single characters finds "aba" but never "abba". Every centre has to be tried twice — once on a character, once on the gap after it.

O(n2) time, O(1) space. Manacher's algorithm gets to O(n), and is worth naming in an interview, but expand-around-centre is what you should be able to write from memory.

abba 4 centres on a character → odd-length palindromes 3 centres in a gap → even-length palindromes expand Expanding from the middle gap matches b=b, then a=a → "abba", length 4.
There are 2n-1 centres, not n. Expanding only from characters finds "aba" and never finds "abba".

Anagram checks by counting

Two strings are anagrams when they have identical character counts. Sorting both and comparing works at O(n log n); counting works at O(n) and is the answer to give.

Anagram check for lowercase a–z
boolean isAnagram(String a, String b) {
    if (a.length() != b.length()) return false;   // cheap early exit

    int[] count = new int[26];
    for (int i = 0; i < a.length(); i++) {
        count[a.charAt(i) - 'a']++;
        count[b.charAt(i) - 'a']--;               // one pass over both
    }
    for (int c : count) if (c != 0) return false;
    return true;
}
warn

The 26-slot assumption

A fixed int[26] is only valid for lowercase ASCII letters. For Unicode, mixed case, digits or spaces, use a hash map — and say out loud which assumption you are making, because interviewers usually ask.

Key takeaways

  • Palindrome checks are two pointers converging from both ends: O(n) time, O(1) space.
  • Longest palindromic substring: expand around all 2n-1 centres, odd and even.
  • Anagram checks are frequency counts, O(n), and beat sorting at O(n log n).
  • State your alphabet assumption before using a fixed-size count array.

Practice

ProblemPatternLevel
Valid palindromeTwo pointersEasy
Valid anagramFrequency countEasy
Group anagramsSorted key + hash mapMedium
Longest palindromic substringExpand around centreMedium
Palindromic substrings countExpand around centreMedium

Frequently asked questions

How do you check if a string is a palindrome?

Put one pointer at each end and walk them inwards, comparing characters and skipping anything you were told to ignore. If every compared pair matches, it is a palindrome. O(n) time, O(1) space.

What is the best way to check if two strings are anagrams?

Count character frequencies in one pass, incrementing for the first string and decrementing for the second, then check that every count ended at zero. That is O(n), against O(n log n) for sorting both.

How do you find the longest palindromic substring?

Expand around each of the 2n-1 possible centres, remembering the longest match. That is O(n squared) with O(1) space; Manacher's algorithm reduces it to O(n).

Test yourself on Strings

Reading is not recall. Take a timed quiz on this topic solo, or share a room code and battle friends on it.

⚡ Start the Strings quiz

More in Strings