Count characters to compare strings and check palindromes.
Use it when the question is about which characters a text holds, and not about where they are. Signal words: same letters, rearrange, anagram, how often, at most one odd count.
Start an array of counts, one for each possible character, all 0. Use a map when the alphabet is large.
Step add one for each character of the first text. Take one away for each character of the second, or compare the counts.
Stop after both walks. Read the counts: all 0, or the number of odd counts.
It does not answer questions about order, such as whether one word is a substring of another. Those need pointers or a window.
Cost: O(n) time, and O(1) extra space for a fixed alphabet.
In this lesson you compare texts by counting their letters. You check whether two words use the same letters, and whether a text reads the same from both ends.
You work on the search of an online store. Listings carry tag words, and shoppers sometimes type the letters of a tag in a different order. The store wants to know when two words use exactly the same letters, for example stone and tones.
Your team lead says: Tell me whether the typed word is a rearrangement of the listing tag. Long product tags can reach 100,000 letters, and the search must answer at once.
Here is a short test: stone and tones use the same letters, and stone and stood do not. All letters are lowercase, from a to z.
Two players each hold a bag of letter tiles. They want to know whether the bags hold the same tiles, in any order.
Each player tips the tiles on a table and tallies them on a sheet with one row for each letter. The bags are the same exactly when the two sheets agree in every row. The sheet is the counting array, and each row is the count of one letter.
Like two bags of letter tiles: tally each bag on a sheet with a row for each letter. The bags match when the sheets agree.
Before you write code, check stone and tones by hand. Keep one tally for each letter. The first word adds to the tally, and the second word takes from it.
Solve it by hand: Two words checked with a count for each letter. The hand-solve sheet loads in your browser.
If both words use the same letters, every tally ends at 0. A tally that is not 0 names a letter that one word has more of.
The words are stone and tones. The table shows the number of letters whose tally is not 0 after each step.
| Step | Letter | Action | Letters with a tally not 0 |
|---|---|---|---|
| 1 | s | first word: add one | 1 |
| 2 | t | first word: add one | 2 |
| 3 | o | first word: add one | 3 |
| 4 | n | first word: add one | 4 |
| 5 | e | first word: add one | 5 |
| 6 | t | second word: take one away | 4 |
| 7 | o | second word: take one away | 3 |
| 8 | n | second word: take one away | 2 |
| 9 | e | second word: take one away | 1 |
| 10 | s | second word: take one away | 0 |
Every tally is 0, so the words use the same letters.
Start with a correct version. For each letter of the first word, count it in the first word and in the second word, and check that the two counts agree.
def same_letters_first(first, second):
if len(first) != len(second):
return False
for letter in first:
if first.count(letter) != second.count(letter): # two scans for every letter
return False
return TrueThis is correct. On stone and tones it makes 50 steps, which is instant.
Now check the real size.
A long tag has 100,000 letters. The typed word has 100,000 letters too.
Here is the count from running the code:
So a single check on a long tag needs twenty billion steps, far more than "at once".
Predict the cost
Q The first attempt scans both words for every letter. How does the number of steps grow when the words have twice as many letters?
Answer: B
The steps are 2 * n * n, so doubling n multiplies them by about 4. The 26 letters bound the number of different letters, but the code scans for every position, not for every different letter.
The first attempt is correct, but it counts the same letter again for every position. Now look at what one tally sheet needs.
Look at the hand trace again. Each letter was handled once, and the tally told the whole story. There was no need to scan a word again.
So keep an array of counts, one for each of the 26 letters. Walk the first word and add one for each letter. Walk the second word and take one away for each letter.
The key fact is about the lengths. If the words have the same length, and no count ever goes below 0 while you take letters away, then every count ends at 0. The words then use the same letters.
Here is the same long tag, counted in each way:
| Method | Steps for 100,000 letters |
|---|---|
| Scan both words for every letter | 20,000,000,000 |
| Sort both words and compare | about 1,660,964 comparisons for each sort |
| One counting pass | 200,000 |
Sorting works and is simple. Counting is linear, so it wins for a small alphabet.
Race: Comparing two words: count each letter by scanning against one counting pass. The operation counter loads in your browser.
At 1,000 letters the first attempt takes 2,000,000 steps and the counting pass 2,000. At 10,000 letters the counts are 200,000,000 against 20,000.
Count the first word up and the second word down. If every count ends at zero, the words use the same letters.
A second job checks a phrase that reads the same from both ends. Spaces do not count, and upper and lower case are the same letter. The phrase is Taco cat, and the player shows the space as an underscore. It stops at four steps and asks you where a pointer is.
Dry run: Predict each step: a phrase with a space. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Pair | Left | Right | Letters compared | Result |
|---|---|---|---|---|
| 1 | 0 | 7 | T and t | equal |
| 2 | 1 | 6 | a and a | equal |
| 3 | 2 | 5 | c and c | equal |
| 4 | 3 | 4 | o and a space: the right pointer skips to 3 | o and o: equal |
After the fourth pair the pointers have crossed, so every pair matched. The phrase is a palindrome.
An array of counts needs a place for every possible character. For 26 lowercase letters or 128 ASCII characters that is tiny. For Unicode, or for whole words, the alphabet is far too large, and a map from character to count is the right tool. The idea does not change: a count for each key.
Here is the rule that keeps these checks correct. Every line of the templates exists to protect it.
A count for each letter says how many times it occurs. Two words use the same letters exactly when all their counts agree, and a palindrome is a text that matches itself from both ends.
At the start every count is 0. Adding a letter raises its count, and taking a letter lowers it. A word is a rearrangement of another exactly when the two walks cancel out.
For a palindrome, the ends must match and the same holds for everything between them. That is why two pointers moving inwards check the whole text.
Use it when the question is about which characters a text holds, and not about where they are. Signal words: same letters, rearrange, anagram, how often, at most one odd count.
Start: an array of counts, one for each possible character, all 0. Use a map when the alphabet is large.
Step: add one for each character of the first text. Take one away for each character of the second, or compare the counts.
Stop: after both walks. Read the counts: all 0, or the number of odd counts.
It does not answer questions about order, such as whether one word is a substring of another. Those need pointers or a window.
Cost: O(n) time, and O(1) extra space for a fixed alphabet.
The alphabet is the lowercase letters a to z, so ord(ch) - 97 gives a place from 0 to 25. Any other character needs a larger array or a map.
def same_letters(first, second):
# [1] Words of different lengths cannot match. Keep one count for each of the 26 letters.
if len(first) != len(second):
return False
counts = [0] * 26
# [2] Add one for every letter of the first word.
for ch in first:
counts[ord(ch) - 97] += 1
# [3] Take one away for every letter of the second word. A count below 0 means the second word has an extra letter.
for ch in second:
counts[ord(ch) - 97] -= 1
if counts[ord(ch) - 97] < 0:
return False
# [4] With equal lengths and no count below 0, every count is 0: the words use the same letters.
return Truepublic boolean sameLetters(String first, String second) {
// [1] Words of different lengths cannot match. Keep one count for each of the 26 letters.
if (first.length() != second.length()) {
return false;
}
int[] counts = new int[26];
// [2] Add one for every letter of the first word.
for (int i = 0; i < first.length(); i++) {
counts[first.charAt(i) - 'a']++;
}
// [3] Take one away for every letter of the second word. A count below 0 means the second word has an extra letter.
for (int i = 0; i < second.length(); i++) {
counts[second.charAt(i) - 'a']--;
if (counts[second.charAt(i) - 'a'] < 0) {
return false;
}
}
// [4] With equal lengths and no count below 0, every count is 0: the words use the same letters.
return true;
}bool sameLetters(string first, string second) {
// [1] Words of different lengths cannot match. Keep one count for each of the 26 letters.
if (first.size() != second.size()) {
return false;
}
vector<int> counts(26, 0);
// [2] Add one for every letter of the first word.
for (char ch : first) {
counts[ch - 'a']++;
}
// [3] Take one away for every letter of the second word. A count below 0 means the second word has an extra letter.
for (char ch : second) {
counts[ch - 'a']--;
if (counts[ch - 'a'] < 0) {
return false;
}
}
// [4] With equal lengths and no count below 0, every count is 0: the words use the same letters.
return true;
}function sameLetters(first, second) {
// [1] Words of different lengths cannot match. Keep one count for each of the 26 letters.
if (first.length !== second.length) {
return false;
}
const counts = new Array(26).fill(0);
// [2] Add one for every letter of the first word.
for (const ch of first) {
counts[ch.charCodeAt(0) - 97]++;
}
// [3] Take one away for every letter of the second word. A count below 0 means the second word has an extra letter.
for (const ch of second) {
counts[ch.charCodeAt(0) - 97]--;
if (counts[ch.charCodeAt(0) - 97] < 0) {
return false;
}
}
// [4] With equal lengths and no count below 0, every count is 0: the words use the same letters.
return true;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Break it: The word with a spare letter. This anagram check counts the first word up and the second word down, but it skips the length test. Find two words where it says yes and the answer is no.
def same_letters(first, second):
counts = [0] * 26
for ch in first:
counts[ord(ch) - 97] += 1
for ch in second:
counts[ord(ch) - 97] -= 1
if counts[ord(ch) - 97] < 0:
return False
return TrueThe rules are exact. The text holds ASCII letters and spaces only. Spaces do not count, and an upper-case letter equals its lower-case letter. Beyond ASCII, the four languages fold case differently, so state the alphabet first.
def is_phrase_palindrome(text):
# [1] Put one pointer at each end.
left = 0
right = len(text) - 1
# [2] Work inwards until the pointers meet.
while left < right:
# [3] Move each pointer past spaces, which do not count.
while left < right and text[left] == " ":
left += 1
while left < right and text[right] == " ":
right -= 1
# [4] Compare the two letters, ignoring upper and lower case. A difference means no palindrome.
if text[left].lower() != text[right].lower():
return False
# [5] Move both pointers one step inwards.
left += 1
right -= 1
# [6] Every pair matched, so the text reads the same both ways.
return Truepublic boolean isPhrasePalindrome(String text) {
// [1] Put one pointer at each end.
int left = 0;
int right = text.length() - 1;
// [2] Work inwards until the pointers meet.
while (left < right) {
// [3] Move each pointer past spaces, which do not count.
while (left < right && text.charAt(left) == ' ') {
left++;
}
while (left < right && text.charAt(right) == ' ') {
right--;
}
// [4] Compare the two letters, ignoring upper and lower case. A difference means no palindrome.
if (Character.toLowerCase(text.charAt(left)) != Character.toLowerCase(text.charAt(right))) {
return false;
}
// [5] Move both pointers one step inwards.
left++;
right--;
}
// [6] Every pair matched, so the text reads the same both ways.
return true;
}bool isPhrasePalindrome(string text) {
// [1] Put one pointer at each end.
int left = 0;
int right = (int)text.size() - 1;
// [2] Work inwards until the pointers meet.
while (left < right) {
// [3] Move each pointer past spaces, which do not count.
while (left < right && text[left] == ' ') {
left++;
}
while (left < right && text[right] == ' ') {
right--;
}
// [4] Compare the two letters, ignoring upper and lower case. A difference means no palindrome.
if (tolower((unsigned char)text[left]) != tolower((unsigned char)text[right])) {
return false;
}
// [5] Move both pointers one step inwards.
left++;
right--;
}
// [6] Every pair matched, so the text reads the same both ways.
return true;
}function isPhrasePalindrome(text) {
// [1] Put one pointer at each end.
let left = 0;
let right = text.length - 1;
// [2] Work inwards until the pointers meet.
while (left < right) {
// [3] Move each pointer past spaces, which do not count.
while (left < right && text[left] === " ") {
left++;
}
while (left < right && text[right] === " ") {
right--;
}
// [4] Compare the two letters, ignoring upper and lower case. A difference means no palindrome.
if (text[left].toLowerCase() !== text[right].toLowerCase()) {
return false;
}
// [5] Move both pointers one step inwards.
left++;
right--;
}
// [6] Every pair matched, so the text reads the same both ways.
return true;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: Taco cat is not a palindrome. This phrase check answers no for "Taco cat", a phrase that reads the same from both ends. Which line is wrong?
def is_phrase_palindrome(text):
left = 0
right = len(text) - 1
while left < right:
while left < right and text[left] == " ":
left += 1
while left < right and text[right] == " ":
right -= 1
if text[left] != text[right]:
return False
left += 1
right -= 1
return TrueExercise · Predict the output: Where do the pointers stop?. The loop stops at the first pair of letters that differ. What does this print?
text = "Race a car"
left, right = 0, len(text) - 1
while left < right:
while left < right and text[left] == " ":
left += 1
while left < right and text[right] == " ":
right -= 1
if text[left].lower() != text[right].lower():
break
left += 1
right -= 1
print(left, right)To check a phrase, put one pointer at each end, skip spaces, compare the two letters ignoring case, and move both inwards until they meet.
The code holds the lowercase letters a to z only, as in template 1.
def can_rearrange_to_palindrome(code):
# [1] Keep one count for each of the 26 letters.
counts = [0] * 26
# [2] Count every letter once.
for ch in code:
counts[ord(ch) - 97] += 1
# [3] Count the letters that occur an odd number of times.
odd_letters = 0
for count in counts:
if count % 2 == 1:
odd_letters += 1
# [4] A palindrome has at most one letter in the middle, so at most one odd count is allowed.
return odd_letters <= 1public boolean canRearrangeToPalindrome(String code) {
// [1] Keep one count for each of the 26 letters.
int[] counts = new int[26];
// [2] Count every letter once.
for (int i = 0; i < code.length(); i++) {
counts[code.charAt(i) - 'a']++;
}
// [3] Count the letters that occur an odd number of times.
int oddLetters = 0;
for (int count : counts) {
if (count % 2 == 1) {
oddLetters++;
}
}
// [4] A palindrome has at most one letter in the middle, so at most one odd count is allowed.
return oddLetters <= 1;
}bool canRearrangeToPalindrome(string code) {
// [1] Keep one count for each of the 26 letters.
vector<int> counts(26, 0);
// [2] Count every letter once.
for (char ch : code) {
counts[ch - 'a']++;
}
// [3] Count the letters that occur an odd number of times.
int oddLetters = 0;
for (int count : counts) {
if (count % 2 == 1) {
oddLetters++;
}
}
// [4] A palindrome has at most one letter in the middle, so at most one odd count is allowed.
return oddLetters <= 1;
}function canRearrangeToPalindrome(code) {
// [1] Keep one count for each of the 26 letters.
const counts = new Array(26).fill(0);
// [2] Count every letter once.
for (const ch of code) {
counts[ch.charCodeAt(0) - 97]++;
}
// [3] Count the letters that occur an odd number of times.
let oddLetters = 0;
for (const count of counts) {
if (count % 2 === 1) {
oddLetters++;
}
}
// [4] A palindrome has at most one letter in the middle, so at most one odd count is allowed.
return oddLetters <= 1;
}Exercise · Put it in order: The lucky ride code. Arrange the lines into a check that says whether the letters of a code can be rearranged into a palindrome.
def can_rearrange_to_palindrome(code):
counts = [0] * 26
odd_letters = 0
for ch in code:
counts[ord(ch) - 97] += 1
for count in counts:
if count % 2 == 1:
odd_letters += 1
return odd_letters <= 1
return odd_letters == 1The three templates answer three kinds of question. You can pick before you write any code.
Then check the ends: what do the templates do on empty texts, on one letter, and on letters of different case?
| Situation | Method | Why |
|---|---|---|
| Same letters in any order | Count up and down | One pass for each word |
| Reads the same both ways | Two pointers | Each pair is checked once |
| Rearrange into a palindrome | At most one odd count | The middle takes one letter |
| Many words with the same letters | The sorted letters as a key, or a count key | Equal keys mean equal letters |
A ride receipt carries the code aabbc. A ride is lucky when the letters can be rearranged into a palindrome.
Use template 3.
| Letter | Count | Odd? |
|---|---|---|
| a | 2 | no |
| b | 2 | no |
| c | 1 | yes |
One letter has an odd count, so the answer is yes. A palindrome is abcba, with c in the middle.
Real data brings edge cases.
For first = "ab" and second = "a" the lengths differ, so the answer is false at once. The check also keeps the counts honest: without it, the second walk would finish with no count below 0.
For first = "" and second = "", no letter is counted, every count is 0, and the answer is true. For text = "" the pointers start crossed, and the answer is true.
Stone and tones use the same letters only if S and s are the same letter. Template 1 assumes lowercase a to z. If case does not matter, change both words to lowercase first.
A word such as café has an accented letter that would index outside the array of 26 counts. Use a map from character to count, and state which alphabet the task uses.
This version checks that both words use the same set of different letters, and ignores how often each occurs.
Counterexample: aab and abb use the letters a and b in both words, but a occurs twice in the first and once in the second. They are not rearrangements of each other.
Compare how often each letter occurs, not only which letters occur.
This version adds up the letter codes of each word and compares the two sums. Different letters can give the same sum.
Counterexample: ad and bc. The codes are 97 + 100 = 197 and 98 + 99 = 197, so the sums agree, but the words use different letters.
A sum loses information. Keep a count for each letter.
Adding up the letter codes loses information: different letters can give the same sum, so two words that are not rearrangements can look equal.
This version compares the text with its reverse as it is. The space and the capital letter break the match.
Counterexample: Taco cat. The reverse is tac ocaT, which is different, but the phrase is a palindrome when spaces and case are ignored.
State what counts, and skip or fold the rest with two pointers.
This version says that a text can be rearranged into a palindrome only when every count is even. That is true for an even length, and false for an odd one.
Counterexample: aab. The count of b is odd, so the version says no. But aba is a palindrome, with b in the middle.
Allow at most one odd count.
The store wants to know whether the typed word is a part of the tag, such as one inside stone. Counting letters cannot tell, because it forgets the order.
Use a window or a substring search instead. Counting answers questions about which characters, never where they are.
Your team lead brings four product changes.
Many tags must be grouped so that tags with the same letters share a group. Use the sorted letters, or a tuple of 26 counts, as a key in a map. This is LeetCode 49: Group Anagrams, and the built problem group-the-product-codes-by-letters practises it.
A long log must be searched for every place where a short word appears in any letter order. Keep the counts of a window of the word's length, and slide it. This is LeetCode 438: Find All Anagrams in a String, and the built problem find-all-anagram-starts-in-a-log practises it.
A shopper has a pool of letters, and wants to know which words can be made from it. Count the pool, then count each word and check that no letter is needed more often than the pool has it. This is LeetCode 383: Ransom Note, and the built problem words-made-from-a-letter-pool practises it.
Given letters, find the length of the longest palindrome that can be built from them. Use every pair of equal letters, and add one more letter in the middle if any count is odd. This is LeetCode 409: Longest Palindrome.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you check whether two words use the same letters. Then say what it costs, and when you would use a map in place of an array. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
I keep one count for each letter. I add one for every letter of the first word, and take one away for every letter of the second word.
If the lengths match and no count goes below zero, every count ends at zero, so the words use the same letters. That costs O of n time and O of 1 space for a fixed alphabet.
If the alphabet is large, such as Unicode, I use a map in place of the array. Sorting both words also works, in O of n log n.
To check whether two words use the same letters, I count. I keep an array with one count for each letter. I add one for every letter of the first word, and take one away for every letter of the second word.
If the lengths differ, the answer is no. Otherwise, if no count ever goes below zero, every count ends at zero, and the words are rearrangements of each other. That costs O of n time and constant space for a fixed alphabet. Sorting both words works too, but it costs O of n log n.
For a palindrome, I put one pointer at each end and move inwards, skipping characters that do not count. To ask whether the letters can be rearranged into a palindrome, I count the letters, and allow at most one odd count.
I state my assumptions: ASCII letters, and whether case and spaces matter. For a large alphabet, I use a map.
Checkpoint · Strings and builders
Q1/3 A loop puts each of 100,000 codes of 10 characters in front of a report string. Why is it slow in Python, Java and C++?
Answer: B
A string cannot change, so putting a code in front makes a new string and copies the old text. A builder writes 1,100,000 characters once.
Q2/3 You join "x", "y" and "z" with a comma, and the result is "x,y,z,". What went wrong?
Answer: C
Put the separator before every piece except the first. Then no separator follows the last piece.
Q3/3 The text is "naïve", stored as UTF-8. What do Python len and C++ std::string size() return?
Answer: B
Python counts code points, so it is 5. A C++ std::string counts bytes, and ï takes 2 bytes in UTF-8, so it is 6.
Checkpoint · Frequency, palindromes and anagrams
Q1/7 The words are "stone" and "tones". You add one for each letter of the first word and take one away for each letter of the second. What ends up in every count?
Answer: C
Each letter that the first word adds is taken away once by the second word, so every count ends at 0.
Q2/7 Scanning both words for every letter costs 2 * n * n steps. About how many steps is that for two words of 100,000 letters?
Answer: C
2 * 100,000 * 100,000 = 20,000,000,000. One counting pass costs 200,000.
Q3/7 Why does the count template compare the lengths of the two words first?
Answer: B
If the second word is a part of the first, no count goes below 0, but the first word still has letters left. The length check closes that gap.
Q4/7 You must compare two texts in Unicode. Which structure holds the counts?
Answer: C
A small, fixed alphabet fits an array. A large or unknown alphabet needs a map. The idea is the same: a count for each key.
Q5/7 Which pair of words shows that comparing only the sets of letters is wrong?
Answer: B
Both use the letters a and b, but a occurs twice in the first word and once in the second. The counts differ.
Q6/7 You check "Taco cat" with spaces ignored and upper and lower case treated as the same. Which step handles the space in the middle?
Answer: B
The right pointer meets the space at place 4 and moves to place 3, where the letter o is.
Q7/7 The letter counts of a text are 2, 2 and 1. Can the letters be rearranged into a palindrome?
Answer: B
The single odd letter goes in the middle, as in abcba. A text can be rearranged into a palindrome when at most one count is odd.
Ten questions on this lesson and the strings lesson before it. Pass with 80% or more to be sure the ideas have landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Same letters different order | Search | Easy | Counting up and down |
| 2 | Can the ticket be a palindrome | Rides | Easy | At most one odd count |
| 3 | Sort the buckets of a histogram | Observe | Easy | Counts that drive the output order |
More practice on this lesson, already built: isomorphic-status-codes, words-that-are-rotations-of-each-other, group-strings-that-differ-by-the-same-shift, find-all-anagram-starts-in-a-log and words-made-from-a-letter-pool. The built problem group-the-product-codes-by-letters closes this stretch as part of its checkpoint, with adding two long numbers as text.
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.