0
0
CProgramBeginner · 2 min read

C Program to Check Anagram with Example and Explanation

A C program to check an anagram compares two strings by counting characters using arrays; for example, use int count[256] = {0}; to track characters and verify if both strings have the same counts.
📋

Examples

Inputstr1 = "listen", str2 = "silent"
OutputAnagram
Inputstr1 = "hello", str2 = "bello"
OutputNot an Anagram
Inputstr1 = "aabbcc", str2 = "abcabc"
OutputAnagram
🧠

How to Think About It

To check if two words are anagrams, think of counting how many times each letter appears in both words. If both have the same counts for every letter, they are anagrams. If any count differs, they are not.
📐

Algorithm

1
Get two input strings.
2
Check if their lengths are equal; if not, they cannot be anagrams.
3
Create an array to count characters for the first string by increasing counts.
4
Decrease counts for characters found in the second string.
5
If all counts return to zero, the strings are anagrams; otherwise, they are not.
💻

Code

c
#include <stdio.h>
#include <string.h>

int isAnagram(char *str1, char *str2) {
    int count[256] = {0};
    int i;
    if (strlen(str1) != strlen(str2))
        return 0;
    for (i = 0; str1[i] && str2[i]; i++) {
        count[(unsigned char)str1[i]]++;
        count[(unsigned char)str2[i]]--;
    }
    for (i = 0; i < 256; i++) {
        if (count[i] != 0)
            return 0;
    }
    return 1;
}

int main() {
    char str1[100], str2[100];
    printf("Enter first string: ");
    scanf("%99s", str1);
    printf("Enter second string: ");
    scanf("%99s", str2);
    if (isAnagram(str1, str2))
        printf("Anagram\n");
    else
        printf("Not an Anagram\n");
    return 0;
}
🔍

Dry Run

Let's trace the example where str1 = "listen" and str2 = "silent" through the code.

1

Check length

Both strings have length 6, so continue.

2

Count characters in str1 and str2

For each character in str1, increment count; for str2, decrement count.

3

Verify counts

All counts are zero, so strings are anagrams.

CharacterCount after str1 incrementCount after str2 decrement
l10
i10
s10
t10
e10
n10
💡

Why This Works

Step 1: Length Check

If the two strings have different lengths, they cannot be anagrams, so we return false immediately.

Step 2: Counting Characters

We use an array to count how many times each character appears in the first string and subtract counts for the second string.

Step 3: Final Verification

If all counts are zero, it means both strings have the same characters in the same quantity, confirming they are anagrams.

🔄

Alternative Approaches

Sorting both strings
c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int cmpfunc(const void *a, const void *b) {
    return (*(char*)a - *(char*)b);
}

int isAnagram(char *str1, char *str2) {
    int len1 = strlen(str1), len2 = strlen(str2);
    if (len1 != len2) return 0;
    qsort(str1, len1, sizeof(char), cmpfunc);
    qsort(str2, len2, sizeof(char), cmpfunc);
    return strcmp(str1, str2) == 0;
}

int main() {
    char str1[100], str2[100];
    printf("Enter first string: ");
    scanf("%99s", str1);
    printf("Enter second string: ");
    scanf("%99s", str2);
    if (isAnagram(str1, str2))
        printf("Anagram\n");
    else
        printf("Not an Anagram\n");
    return 0;
}
Sorting is simple and intuitive but slower (O(n log n)) compared to counting (O(n)).
Using a hash map (dictionary) for counting
c
#include <stdio.h>
#include <string.h>

int isAnagram(char *str1, char *str2) {
    int count[256] = {0};
    int i;
    if (strlen(str1) != strlen(str2)) return 0;
    for (i = 0; str1[i]; i++) {
        count[(unsigned char)str1[i]]++;
        count[(unsigned char)str2[i]]--;
    }
    for (i = 0; i < 256; i++) {
        if (count[i] != 0) return 0;
    }
    return 1;
}

int main() {
    char str1[100], str2[100];
    printf("Enter first string: ");
    scanf("%99s", str1);
    printf("Enter second string: ");
    scanf("%99s", str2);
    if (isAnagram(str1, str2))
        printf("Anagram\n");
    else
        printf("Not an Anagram\n");
    return 0;
}
This is the main approach shown; it is efficient and uses fixed memory for ASCII.

Complexity: O(n) time, O(1) space

Time Complexity

The program loops through each character of the strings once, so the time is proportional to the string length n.

Space Complexity

It uses a fixed-size array of 256 integers for counting characters, so space is constant O(1).

Which Approach is Fastest?

Counting characters is faster than sorting because it runs in linear time, while sorting takes O(n log n).

ApproachTimeSpaceBest For
Counting charactersO(n)O(1)Fastest for ASCII strings
Sorting stringsO(n log n)O(n)Simple but slower
Hash map countingO(n)O(1)Similar to counting array, good for ASCII
💡
Always check string lengths first to quickly rule out non-anagrams.
⚠️
Forgetting to check string lengths before comparing character counts leads to wrong results.