Count characters to compare strings and check palindromes.
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.
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.
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;
}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;
}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;
}This version checks that both words use the same set of different letters, and ignores how often each occurs.
This version adds up the letter codes of each word and compares the two sums. Different letters can give the same sum.
This version compares the text with its reverse as it is. The space and the capital letter break the match.
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.
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.
systemdesignmastery.dev/dsa/cheatsheets/frequency-palindromes-anagrams