Skip to main content
Intermediate ~14 min read

String Algorithms: Anagrams, Palindromes & Matching

The classic string toolkit: frequency counting, two-pointer palindrome checks, and naive pattern matching, the patterns behind most easy interview strings problems.

Prerequisites: Arrays: Traversal, Insertion & Deletion, Two-Pointer Technique

Almost every classic string problem reduces to one of three moves. Move one: count characters with a frequency map, anagrams, duplicates, "first unique character" are all counting problems in disguise. Move two: converge two pointers from the ends, palindromes and in-place reversals. Move three: slide a window or scan for a pattern, substring search and its relatives.

Recognizing which move applies is the actual skill. "Are these anagrams?" is counting, because order does not matter, only multiset equality. "Is this a palindrome?" is two pointers, because order matters only symmetrically. "Does this pattern appear in this text?" is matching, because position matters exactly. When a new string problem appears, ask: do positions matter, does order matter, does multiplicity matter, and the right tool names itself.

The three moves, implemented

string-toolkit.js
// Move 1, anagrams via frequency count: O(n) time, O(k) space
function isAnagram(a, b) {
  if (a.length !== b.length) return false;
  const count = new Map();
  for (const ch of a) count.set(ch, (count.get(ch) ?? 0) + 1);
  for (const ch of b) {
    const c = count.get(ch) ?? 0;
    if (c === 0) return false;          // b has a char a lacks (or too many)
    count.set(ch, c - 1);
  }
  return true;
}

// Move 2, palindrome via converging pointers: O(n) time, O(1) space
function isPalindrome(s) {
  let left = 0, right = s.length - 1;
  while (left < right) {
    if (s[left] !== s[right]) return false;
    left++; right--;
  }
  return true;
}

// Move 3, naive pattern search: O(n·m) worst case
function findPattern(text, pattern) {
  for (let i = 0; i + pattern.length <= text.length; i++) {
    let j = 0;
    while (j < pattern.length && text[i + j] === pattern[j]) j++;
    if (j === pattern.length) return i;  // full match starting at i
  }
  return -1;
}

Tracing naive pattern search: text "ababc", pattern "abc"

  1. 1

    Align at i = 0

    a=a, b=b, then a≠c → mismatch after 2 comparisons. Shift one position.

  2. 2

    Align at i = 1

    b≠a → mismatch immediately, 1 comparison.

  3. 3

    Align at i = 2

    a=a, b=b, c=c → full match. Return 2. Total comparisons: 3 + 1 + 3 = 7.

  4. 4

    Feel the worst case

    Text "aaaa…a" with pattern "aaab" aligns almost fully at every position before failing, about n·m comparisons. KMP (a follow-up topic) fixes this by never re-examining text characters.

Cost summary

Operation / caseCostNotes
Anagram check (count map)O(n)k = distinct characters, ≤ alphabet size
Anagram check (sort)O(n log n)simpler, slower
Palindrome checkO(n)converging pointers, no allocation
Naive pattern searchO(n·m) worstn = text length, m = pattern length; KMP reaches O(n + m)

Practice

How many character comparisons does the palindrome check do on "racecar" (7 letters)?

Reveal explanation

Pairs (r,r), (a,a), (c,c), 3 comparisons, then left and right cross. The middle character never needs checking. In general ⌊n/2⌋ comparisons.

Check your understanding

  1. 1.What invariant makes the two-pointer palindrome check correct?
  2. 2.Best-case cost of naive pattern search when the pattern's first character never appears in the text?
  3. 3.To find the first non-repeating character in a string, the standard approach is:

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going