Tuesday, 5 April 2011

Detect Anagram in a String



Detect whether a string is anagram of the another string. The normal brute force way would be like this,


bool detect_anagram(char* src, char* anagram)
    int isrc=0, iana=0;
    while(*src != '\0') {
        char* iter = anagram;
        while(*iter != '\0' && *src != ' ') {
            if(*src == *iter) {
        if(*src != ' ')
    if(iana == isrc)
        return true;
        return false;
void main()
    char *src=strdup("eleven plus two");
    char *a = strdup("so plew veluent");
    bool st = detect_anagram(src, a);

Important points

  • The above approach ignores all space character ‘ ‘ and checks for occurrence of a character in the anagram string. If the number of equal characters is equal to the number of characters in source string, then the string is an anagram!!..
  • iter is the iterator for the anagram string
  • We iterate until we find a matching character in the iter. If we find one, we just increment the count and break.
  • iana will be equal to isrc only when characters in source string = anagram string. This is the invariant we need to use to prove the correctness of the above code

Alternate approaches:

  • sort both the strings and check whether both are equal!!
  • Take count of characters in original string first and then start decrementing the count when seeing the same in the anagram string. If the count becomes zero for all the recorded character entries, then the string is an anagram. This approach is little bit faster than our above O(N2) approach.


sathish said...

This just checks if chars in String 1 are in String 2, if there are two a s in String 1 and only one a in String 2 it ll still give it as an anagram. so its wrong

vprajan said...

yep.. the approach won't work if the string lengths are not equal.. we need to have a check to verify whether the length of the string is equal

Post a Comment