Challenge: Anagram Check
Completed
Read two words (lowercase letters) and print anagram if they use exactly the same letters, otherwise not anagram. Count the letters with an array of 26.
Input
Two words.
Output
anagram or not anagram.
Example
Input
listen silent
Output
anagram
Editor
C++
Hints
Add 1 for each letter of a, subtract 1 for each letter of b.
Anagrams leave every counter at 0.
Solution explanation
O(n) – faster than sorting both words.
Show solution
#include <iostream>
#include <string>
using namespace std;
int main() {
string a, b;
cin >> a >> b;
int count[26] = {0};
for (char c : a) count[c - 'a']++;
for (char c : b) count[c - 'a']--;
bool same = true;
for (int x : count)
if (x != 0) same = false;
cout << (same ? "anagram" : "not anagram") << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module