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
// 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
Align at i = 0
a=a, b=b, then a≠c → mismatch after 2 comparisons. Shift one position.
- 2
Align at i = 1
b≠a → mismatch immediately, 1 comparison.
- 3
Align at i = 2
a=a, b=b, c=c → full match. Return 2. Total comparisons: 3 + 1 + 3 = 7.
- 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 / case | Cost | Notes |
|---|---|---|
| Anagram check (count map) | O(n) | k = distinct characters, ≤ alphabet size |
| Anagram check (sort) | O(n log n) | simpler, slower |
| Palindrome check | O(n) | converging pointers, no allocation |
| Naive pattern search | O(n·m) worst | n = 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.