C PROGRAMMING PROGRAM • STRINGS
Check Whether Two Strings Are Anagrams
Learn how to check whether two strings are anagrams using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
Dormitory Dirty room
Sample output
Anagrams
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Anagrams
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Add character frequencies from the first text and subtract those from the second, ignoring case and spaces.
- 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.
