Strings, Characters & Anagrams
Data Structures & Algorithms · Arrays & Strings · Basics · 16 min
Treat strings like arrays of characters: count letters with a frequency map, spot anagrams and palindromes, and build strings without hidden O(n²) costs.
Pour the letters of each word into its own row of labelled jars, one jar per letter. Two words are anagrams exactly when every jar holds the same number of tiles.
The idea in everyday words
Think of Scrabble tiles. 'listen' and 'silent' look different on the board, but if you tip both sets of tiles into piles sorted by letter, the piles are identical. Comparing piles is much easier than trying every way of rearranging the letters.
A string is a row of characters that never changes
A string is a sequence, like a list of characters: you can index it (s[0]), slice it (s[1:4]), loop over it and take len(s).
The big difference: strings are immutable. You cannot change a character in place.
s = "cat"
print(s[0], s[-1], s[::-1], len(s))
t = "b" + s[1:] # build a NEW string instead
print(s, t)
print(s.upper(), s.replace("c", "h")) # methods return new strings too
s[0] = "b" would raise a TypeError. Every "change" really builds a new string.
Each character is stored as a number (its code point). ord("a") is 97 and chr(97) is "a". So ord(ch) - ord("a") turns a..z into 0..25, perfect for an array of 26 counters.
Counting characters: the frequency map
So many string problems become easy once you ask: "how many of each character are there?"
word = "banana"
count = {}
for ch in word:
count[ch] = count.get(ch, 0) + 1
print(count)
from collections import Counter
print(Counter(word).most_common(1))
arr = [0] * 26 # fixed alphabet: an array of 26 counters
for ch in word:
arr[ord(ch) - ord("a")] += 1
print(arr[:3]) # counts of a, b, c
dict/Counter: works for any characters.[0] * 26: slightly faster, only for lowercase a-z. Its space is O(1) because 26 never grows with the input.
Frequency maps answer: anagrams, "first unique character", "can I build this note from these letters?", "most common letter".
Anagrams: same letters, different order
Two strings are anagrams if one is a rearrangement of the other: listen / silent.
Three ways to check, from slowest to fastest:
| Idea | Cost | Notes |
|---|---|---|
| Try every rearrangement | O(n!) | hopeless after ~10 letters |
| Sort both, compare | O(n log n) | sorted(s) == sorted(t), simple and fine |
| Count letters, compare | O(n) | one counter: +1 for s, -1 for t, all must be 0 |
def is_anagram(s, t):
if len(s) != len(t):
return False # quick exit
count = {}
for ch in s:
count[ch] = count.get(ch, 0) + 1
for ch in t:
count[ch] = count.get(ch, 0) - 1
if count[ch] < 0:
return False # t has an extra ch
return True
print(is_anagram("listen", "silent"), is_anagram("rat", "car"))
Why the early return is safe: the lengths match, so if no count ever goes negative, every count must end at exactly 0.
Grouping anagrams: give every word a signature that anagrams share (its sorted letters, or its 26 counts as a tuple), then group words by signature in a dict.
Palindromes: the same both ways
A palindrome reads the same forwards and backwards: racecar, noon.
- Quick way:
s == s[::-1](builds a reversed copy, O(n) extra space). - Interview way: two pointers from both ends moving inward, O(1) extra space.
def is_palindrome(s):
i, j = 0, len(s) - 1
while i < j:
if not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
elif s[i].lower() != s[j].lower():
return False
else:
i += 1
j -= 1
return True
print(is_palindrome("A man, a plan, a canal: Panama"), is_palindrome("hello"))
Interviewers love the "ignore punctuation and case" version: the trick is skipping characters inside the loop instead of building a cleaned copy.
A counting fact worth remembering: letters can be rearranged into a palindrome if at most one letter has an odd count.
Building strings efficiently
Because strings are immutable, result += ch inside a loop may copy the whole string every time. For n characters that can add up to O(n²).
The fix: collect pieces in a list, then join once.
words = ["fast", "string", "building"]
parts = []
for w in words:
parts.append(w.upper())
print("-".join(parts)) # one O(n) join
print("".join(reversed("stressed")))
print(" ".join(" too many spaces ".split()))
(CPython sometimes optimises += on strings, but you cannot rely on it, and other languages do not. In Java use StringBuilder.)
Useful built-ins: split, join, strip, lower, isalnum, isdigit, startswith, find.
Step by step
- Check lengths:
s = 'listen', t = 'silent'. Both have 6 letters, so an anagram is still possible.
- Count s:
Walk 'listen' adding 1 per letter: l:1, i:1, s:1, t:1, e:1, n:1.
- Subtract t: 's':
First letter of 'silent' is s: s goes 1 → 0. Not negative, continue.
- Subtract the rest:
i, l, e, n, t each go 1 → 0. No count ever drops below 0.
- Answer:
Every counter is 0, so the letters match exactly: True.
- Contrast: rat vs car:
After counting 'rat' (r:1, a:1, t:1), subtracting 'car' hits c: 0 → -1. t has a letter s does not, so return False right away.
Code example
from collections import Counter
def is_anagram(s, t):
if len(s) != len(t):
return False
count = {}
for ch in s:
count[ch] = count.get(ch, 0) + 1
for ch in t:
count[ch] = count.get(ch, 0) - 1
if count[ch] < 0:
return False
return True
def is_palindrome(s):
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i, j = i + 1, j - 1
return True
print("listen/silent:", is_anagram("listen", "silent"))
print("rat/car:", is_anagram("rat", "car"))
print("counts of 'banana':", dict(Counter("banana")))
print("racecar palindrome?", is_palindrome("racecar"))
groups = {}
for w in ["eat", "tea", "tan", "ate", "nat", "bat"]:
key = "".join(sorted(w)) # anagrams share a signature
groups.setdefault(key, []).append(w)
print("groups:", list(groups.values()))Complexity
- Time: O(n + m): one pass over each string to count, plus a pass over at most k distinct letters to check.
- Space: O(k) for k distinct characters. For lowercase letters only, k ≤ 26, so O(1).
Interview tips
Clarify the alphabet first: 'Only lowercase a-z? Unicode? Do spaces and case matter?' It changes whether a 26-slot array works.
Offer sorting (O(n log n)) as the simple answer, then counting (O(n)) as the optimisation.
Mention that
s += cin a loop can be O(n²) and that you would join a list instead.For 'group anagrams', explain the signature idea: anagrams map to the same key, so a dict of key → list groups them in one pass.
Challenge: Anagram Phrases
Return True if phrases a and b are anagrams of each other when you ignore spaces and upper/lower case. Otherwise return False.
Examples:
is_anagram_phrase("Dormitory", "dirty room")→Trueis_anagram_phrase("aab", "abb")→False
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Valid Anagram (Easy)
- Ransom Note (Easy)
- Valid Palindrome (Easy)
- Group Anagrams (Medium)
More in Arrays & Strings
Previous: Arrays, Memory & Dynamic Arrays · Next: 2D Grids & Matrix Traversal