← All problems · Pointers & Strings
Check Whether Two Strings Are Anagrams
Return 1 if the strings contain the same multiset of bytes, ignoring order but not case or spaces. Assume 8-bit bytes.
Implement int is_anagram(const char *a, const char *b).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Count all byte values using a 256-entry frequency table.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
int is_anagram(const char *a, const char *b)
{
size_t count[256]={0};
for(;*a;++a)++count[(unsigned char)*a];
for(;*b;++b){unsigned char c=(unsigned char)*b;if(!count[c])return 0;--count[c];}
for(size_t i=0;i<256;++i)if(count[i])return 0;
return 1;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <climits>
int is_anagram(const char *a, const char *b)
{
std::size_t count[256]={0};
for(;*a;++a)++count[(unsigned char)*a];
for(;*b;++b){unsigned char c=(unsigned char)*b;if(!count[c])return 0;--count[c];}
for(std::size_t i=0;i<256;++i)if(count[i])return 0;
return 1;
}
Increment for the first string and decrement for the second, rejecting unmatched bytes. Unsigned char indexing avoids negative array indices.
solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
char a[]={(char)0xff,'a',0}, b[]={'a',(char)0xff,0};
CHECK(is_anagram("listen","silent")==1);
CHECK(is_anagram("abc","abb")==0);
CHECK(is_anagram("ab","a")==0);
CHECK(is_anagram("","")==1);
CHECK(is_anagram(a,b)==1);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}