C PROGRAMMING PROGRAM • STRINGS

Check Whether Two Strings Are Anagrams

Learn how to check whether two strings are anagrams using a clear C program.

IntermediateStringsFrequency arrayAnagram

PROBLEM UNDERSTANDING

Input and expected output

Sample input
Dormitory
Dirty room
Sample output
Anagrams

COMPLETE C PROGRAM

Complete C implementation

anagram-check.c
Open in compiler
#include <stdio.h>
#include <ctype.h>

int main(void)
{
    char first[300], second[300];
    int frequency[256] = {0};

    fgets(first, sizeof first, stdin);
    fgets(second, sizeof second, stdin);
    for (int index = 0; first[index] != '\0'; index++) {
        unsigned char value = (unsigned char) first[index];
        if (!isspace(value)) frequency[tolower(value)]++;
    }
    for (int index = 0; second[index] != '\0'; index++) {
        unsigned char value = (unsigned char) second[index];
        if (!isspace(value)) frequency[tolower(value)]--;
    }
    for (int value = 0; value < 256; value++) {
        if (frequency[value] != 0) { printf("Not anagrams\n"); return 0; }
    }
    printf("Anagrams\n");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Anagrams
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Add character frequencies from the first text and subtract those from the second, ignoring case and spaces.
  3. Display the computed result.

Add character frequencies from the first text and subtract those from the second, ignoring case and spaces.

EFFICIENCY

Time and space complexity

Time complexity

O(n+m)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.