Anagram and Frequency Count
In this page:
Anagram Basics
Two strings are anagrams of each other if they contain exactly the same characters with exactly the same frequencies, just rearranged, like listen and silent. Different orderings of the same multiset of characters are what make them anagrams.
Example: Anagram Basics
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string a = "listen", b = "silent";
string sa = a, sb = b;
sort(sa.begin(), sa.end()); sort(sb.begin(), sb.end());
cout << (sa == sb ? "Anagrams" : "Not anagrams") << endl;
return 0;
}
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
char[] a = "listen".toCharArray(), b = "silent".toCharArray();
Arrays.sort(a); Arrays.sort(b);
System.out.println(Arrays.equals(a, b) ? "Anagrams" : "Not anagrams");
}
}
a, b = "listen", "silent"
print("Anagrams" if sorted(a) == sorted(b) else "Not anagrams")
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) { return *(char*)a - *(char*)b; }
int main() {
char a[] = "listen", b[] = "silent";
qsort(a, strlen(a), 1, cmp);
qsort(b, strlen(b), 1, cmp);
printf("%s\n", strcmp(a, b) == 0 ? "Anagrams" : "Not anagrams");
return 0;
}
Login to try C/C++/Java code in the editor
Frequency Count
Frequency simply means counting how many times each distinct character appears in a string, which is the key piece of information needed to compare two strings for the anagram relationship without caring about order.
Example: Frequency Count
#include <iostream>
#include <map>
using namespace std;
int main() {
string s = "banana";
map<char, int> freq;
for (char c : s) freq[c]++;
for (auto& p : freq) cout << p.first << ": " << p.second << endl;
return 0;
}
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
String s = "banana";
TreeMap<Character, Integer> freq = new TreeMap<>();
for (char c : s.toCharArray()) freq.put(c, freq.getOrDefault(c, 0) + 1);
for (var e : freq.entrySet()) System.out.println(e.getKey() + ": " + e.getValue());
}
}
s = "banana"
freq = {}
for c in s:
freq[c] = freq.get(c, 0) + 1
for c, n in sorted(freq.items()):
print(f"{c}: {n}")
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "banana";
int freq[26] = {0};
for (int i = 0; i < strlen(s); i++) freq[s[i] - 'a']++;
for (int i = 0; i < 26; i++) if (freq[i]) printf("%c: %d\n", 'a' + i, freq[i]);
return 0;
}
Login to try C/C++/Java code in the editor
Frequency Array
When the character set is limited, such as lowercase English letters, a fixed-size array of 26 counters (one per letter) can track frequencies in O(1) space relative to the alphabet, making counting extremely fast.
Example: Frequency Array
#include <iostream>
using namespace std;
int main() {
string s = "hello world";
int freq[26] = {0};
for (char c : s) if (c >= 'a' && c <= 'z') freq[c - 'a']++;
cout << "'l' count: " << freq['l' - 'a'] << endl;
return 0;
}
public class Main {
public static void main(String[] args) {
String s = "hello world";
int[] freq = new int[26];
for (char c : s.toCharArray()) if (c >= 'a' && c <= 'z') freq[c - 'a']++;
System.out.println("'l' count: " + freq['l' - 'a']);
}
}
s = "hello world"
freq = [0] * 26
for c in s:
if 'a' <= c <= 'z':
freq[ord(c) - ord('a')] += 1
print("'l' count:", freq[ord('l') - ord('a')])
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "hello world";
int freq[26] = {0};
for (int i = 0; i < strlen(s); i++) if (s[i] >= 'a' && s[i] <= 'z') freq[s[i] - 'a']++;
printf("'l' count: %d\n", freq['l' - 'a']);
return 0;
}
Login to try C/C++/Java code in the editor
Anagram Using Frequency
To check if two strings are anagrams using frequency arrays, count both strings into separate arrays (or increment for one string and decrement for the other) and confirm all counts end at zero, which runs in O(n) time.
Example: Anagram Using Frequency
#include <iostream>
using namespace std;
int main() {
string a = "anagram", b = "nagaram";
int freq[26] = {0};
for (char c : a) freq[c - 'a']++;
for (char c : b) freq[c - 'a']--;
bool isAnagram = true;
for (int i = 0; i < 26; i++) if (freq[i] != 0) isAnagram = false;
cout << (isAnagram ? "Anagrams" : "Not anagrams") << endl;
return 0;
}
public class Main {
public static void main(String[] args) {
String a = "anagram", b = "nagaram";
int[] freq = new int[26];
for (char c : a.toCharArray()) freq[c - 'a']++;
for (char c : b.toCharArray()) freq[c - 'a']--;
boolean isAnagram = true;
for (int f : freq) if (f != 0) isAnagram = false;
System.out.println(isAnagram ? "Anagrams" : "Not anagrams");
}
}
a, b = "anagram", "nagaram"
freq = [0] * 26
for c in a:
freq[ord(c) - ord('a')] += 1
for c in b:
freq[ord(c) - ord('a')] -= 1
print("Anagrams" if all(f == 0 for f in freq) else "Not anagrams")
#include <stdio.h>
#include <string.h>
int main() {
char a[] = "anagram", b[] = "nagaram";
int freq[26] = {0}, isAnagram = 1;
for (int i = 0; i < strlen(a); i++) freq[a[i] - 'a']++;
for (int i = 0; i < strlen(b); i++) freq[b[i] - 'a']--;
for (int i = 0; i < 26; i++) if (freq[i] != 0) isAnagram = 0;
printf("%s\n", isAnagram ? "Anagrams" : "Not anagrams");
return 0;
}
Login to try C/C++/Java code in the editor
Frequency Practice
Frequency counting shows up constantly beyond anagrams too, including finding the most common character, detecting duplicates, and grouping words that are anagrams of each other, so it's worth practicing on plain words first.
Example: Frequency Practice
#include <iostream>
using namespace std;
int main() {
string s = "programming";
int freq[26] = {0};
for (char c : s) freq[c - 'a']++;
int best = 0;
for (int i = 1; i < 26; i++) if (freq[i] > freq[best]) best = i;
cout << "Most common: '" << (char)('a' + best) << "' (" << freq[best] << " times)" << endl;
return 0;
}
public class Main {
public static void main(String[] args) {
String s = "programming";
int[] freq = new int[26];
for (char c : s.toCharArray()) freq[c - 'a']++;
int best = 0;
for (int i = 1; i < 26; i++) if (freq[i] > freq[best]) best = i;
System.out.println("Most common: '" + (char) ('a' + best) + "' (" + freq[best] + " times)");
}
}
s = "programming"
freq = [0] * 26
for c in s:
freq[ord(c) - ord('a')] += 1
best = freq.index(max(freq))
print(f"Most common: '{chr(ord('a') + best)}' ({freq[best]} times)")
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "programming";
int freq[26] = {0};
for (int i = 0; i < strlen(s); i++) freq[s[i] - 'a']++;
int best = 0;
for (int i = 1; i < 26; i++) if (freq[i] > freq[best]) best = i;
printf("Most common: '%c' (%d times)\n", 'a' + best, freq[best]);
return 0;
}
Login to try C/C++/Java code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: