Valid Anagram - C Solution

1. Introduction

In this post, we tackle a classic problem in string manipulation known as the "Valid Anagram" problem. The challenge is to determine if one string is an anagram of another, which means rearranging the letters of one string should form the other string. This problem is a fundamental exercise in understanding string comparison and character counting in C.

Problem

Given two strings s and t, the task is to return true if t is an anagram of s, and false otherwise. An anagram is formed by rearranging the letters of a word or phrase, using all the original letters exactly once.

2. Solution Steps

1. Check if s and t are of the same length. If not, return false.

2. Create an array to count the frequency of each character in s.

3. Increment the frequency for each character in s and decrement for each character in t.

4. If all frequencies are zero at the end, return true. Otherwise, return false.

3. Code Program

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

// Function to check if two strings are anagrams
int isAnagram(char* s, char* t) {
    if (strlen(s) != strlen(t)) return 0;

    int count[256] = {0}; // ASCII characters frequency counter

    for (int i = 0; s[i] != '\0'; i++) {
        count[s[i]]++;
        count[t[i]]--;
    }

    for (int i = 0; i < 256; i++) {
        if (count[i] != 0) return 0;
    }

    return 1;
}

// Main function to test the isAnagram function
int main() {
    char s1[] = "anagram", t1[] = "nagaram";
    printf("Is Anagram (Example 1): %s\n", isAnagram(s1, t1) ? "true" : "false");

    char s2[] = "rat", t2[] = "car";
    printf("Is Anagram (Example 2): %s\n", isAnagram(s2, t2) ? "true" : "false");

    return 0;
}

Output:

Is Anagram (Example 1): true
Is Anagram (Example 2): false

Explanation:

1. First, ensure that s and t are of equal length.

2. Use an array count to track the frequency of each character.

3. Increment the count for characters in s and decrement for characters in t.

4. If all counts are zero, s and t are anagrams of each other.

5. The main function tests isAnagram with two examples and prints the results.


Comments