Bird
Raised Fist0
DSA Cprogramming

Anagram Check Techniques in DSA C

Choose your learning style10 modes available
Mental Model
Two words are anagrams if they have the exact same letters in the same amounts, just mixed up.
Analogy: Imagine two bags of colored beads. If both bags have the same colors and the same number of each color, they are anagrams, even if the beads are arranged differently.
word1: c a t
word2: t a c

Both have letters: c, a, t
Order can differ but counts must match.
Dry Run Walkthrough
Input: word1: "listen", word2: "silent"
Goal: Check if "listen" and "silent" are anagrams by comparing letter counts
Step 1: Count letters in "listen"
l:1, i:1, s:1, t:1, e:1, n:1
Why: We need to know how many times each letter appears in the first word
Step 2: Count letters in "silent"
s:1, i:1, l:1, e:1, n:1, t:1
Why: We count letters in the second word to compare with the first
Step 3: Compare letter counts of both words
Both have l:1, i:1, s:1, t:1, e:1, n:1
Why: If counts match exactly, words are anagrams
Result:
Words are anagrams because letter counts match exactly.
Annotated Code
DSA C
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

#define CHAR_RANGE 256

bool areAnagrams(const char *str1, const char *str2) {
    int count[CHAR_RANGE] = {0};
    int i;

    // If lengths differ, cannot be anagrams
    if (strlen(str1) != strlen(str2))
        return false;

    // Count letters in str1
    for (i = 0; str1[i] != '\0'; i++) {
        count[(unsigned char)str1[i]]++;
    }

    // Subtract counts using str2
    for (i = 0; str2[i] != '\0'; i++) {
        count[(unsigned char)str2[i]]--;
        // If count goes negative, str2 has extra letter
        if (count[(unsigned char)str2[i]] < 0)
            return false;
    }

    // All counts matched
    return true;
}

int main() {
    const char *word1 = "listen";
    const char *word2 = "silent";

    if (areAnagrams(word1, word2))
        printf("%s and %s are anagrams\n", word1, word2);
    else
        printf("%s and %s are NOT anagrams\n", word1, word2);

    return 0;
}
if (strlen(str1) != strlen(str2))
Check if lengths differ -- quick reject if not equal
for (i = 0; str1[i] != '\0'; i++) { count[(unsigned char)str1[i]]++; }
Count each letter in first word
for (i = 0; str2[i] != '\0'; i++) { count[(unsigned char)str2[i]]--; if (count[(unsigned char)str2[i]] < 0) return false; }
Subtract letter counts using second word and check for mismatch
return true;
If no mismatch found, words are anagrams
OutputSuccess
listen and silent are anagrams
Complexity Analysis
Time: O(n) because we count letters in both words once, where n is word length
Space: O(1) because the count array size is fixed (256) regardless of input size
vs Alternative: Sorting both words takes O(n log n), so counting letters is faster and more efficient
Edge Cases
Empty strings
Returns true because two empty strings have matching letter counts
DSA C
if (strlen(str1) != strlen(str2))
Different lengths
Returns false immediately since lengths differ
DSA C
if (strlen(str1) != strlen(str2))
Same letters but different counts (e.g., "aabb" and "aaab")
Returns false because counts mismatch during subtraction
DSA C
if (count[(unsigned char)str2[i]] < 0) return false;
When to Use This Pattern
When you need to check if two words have the same letters in any order, use letter counting to quickly compare their character frequencies.
Common Mistakes
Mistake: Only sorting one word and comparing to the other without sorting it
Fix: Sort both words or use counting for both to ensure accurate comparison
Summary
Checks if two words have the same letters in the same amounts regardless of order.
Use when you want to verify if two strings are anagrams efficiently.
Counting letters and comparing counts is faster than sorting both strings.

Practice

(1/5)
1. What does it mean if two strings are anagrams of each other?
easy
A. They contain the same characters in any order
B. They have the same length but different characters
C. They start with the same character
D. They end with the same character

Solution

  1. Step 1: Understand the definition of anagrams

    Anagrams are words or phrases made by rearranging the letters of another, so they must have the same characters.
  2. Step 2: Compare the character sets

    If two strings have exactly the same characters, just in different orders, they are anagrams.
  3. Final Answer:

    They contain the same characters in any order -> Option A
  4. Quick Check:

    Anagrams = same characters [OK]
Hint: Anagrams have identical letters, order doesn't matter [OK]
Common Mistakes:
  • Thinking length alone defines anagrams
  • Assuming same start or end means anagram
  • Ignoring character counts
2. Which of the following C code snippets correctly checks if two strings are anagrams by sorting?
easy
A. Check only first and last characters
B. Compare lengths only
C. Use strcmp directly without sorting
D. Sort both strings and compare with strcmp

Solution

  1. Step 1: Understand sorting approach

    Sorting both strings puts their characters in order, so if they are anagrams, sorted strings will be identical.
  2. Step 2: Use strcmp to compare sorted strings

    strcmp returns 0 if strings are equal, confirming anagram status.
  3. Final Answer:

    Sort both strings and compare with strcmp -> Option D
  4. Quick Check:

    Sort + strcmp = correct anagram check [OK]
Hint: Sort strings then compare to check anagrams [OK]
Common Mistakes:
  • Comparing strings without sorting
  • Ignoring length check before sorting
  • Using strcmp on unsorted strings
3. What will be the output of the following C code snippet?
#include 
#include 
#include 

bool areAnagrams(char *str1, char *str2) {
    int count[256] = {0};
    int i;
    for (i = 0; str1[i] && str2[i]; i++) {
        count[(unsigned char)str1[i]]++;
        count[(unsigned char)str2[i]]--;
    }
    if (str1[i] || str2[i]) return false;
    for (i = 0; i < 256; i++) {
        if (count[i] != 0) return false;
    }
    return true;
}

int main() {
    if (areAnagrams("listen", "silent"))
        printf("Anagrams\n");
    else
        printf("Not Anagrams\n");
    return 0;
}
medium
A. Anagrams
B. Not Anagrams
C. Compilation error
D. Runtime error

Solution

  1. Step 1: Analyze character counting logic

    The function increments count for each char in str1 and decrements for str2. If strings are anagrams, counts balance to zero.
  2. Step 2: Check string lengths and counts

    Strings "listen" and "silent" have same length and characters, so count array ends with all zeros, returning true.
  3. Final Answer:

    Anagrams -> Option A
  4. Quick Check:

    Balanced counts = anagrams [OK]
Hint: Count chars increment/decrement; zero counts mean anagrams [OK]
Common Mistakes:
  • Not checking string length equality
  • Ignoring unsigned char cast for indexing
  • Returning true without count check
4. Identify the bug in this C function intended to check anagrams:
bool isAnagram(char *s1, char *s2) {
    int count[26] = {0};
    for (int i = 0; s1[i]; i++) {
        count[s1[i] - 'a']++;
        count[s2[i] - 'a']--;
    }
    for (int i = 0; i < 26; i++) {
        if (count[i] != 0) return false;
    }
    return true;
}
medium
A. Missing semicolon in the first for loop
B. Uses int for loop variable instead of size_t
C. Does not check if strings have same length
D. Second loop starts from i=1 instead of i=0

Solution

  1. Step 1: Check loop and length conditions

    The loop runs only while s1[i] is valid, but s2 may be shorter or longer, causing mismatch.
  2. Step 2: Identify missing length check

    Without verifying s1 and s2 have same length, function may incorrectly return true or access invalid memory.
  3. Final Answer:

    Does not check if strings have same length -> Option C
  4. Quick Check:

    Length check missing = bug [OK]
Hint: Always check string lengths before counting chars [OK]
Common Mistakes:
  • Assuming strings are always same length
  • Ignoring null terminator in second string
  • Not handling uppercase letters (less critical here)
5. Given two strings that may contain uppercase, lowercase, and spaces, which approach best checks if they are anagrams ignoring case and spaces?
hard
A. Sort strings directly including spaces and compare
B. Convert both to lowercase, remove spaces, then count characters
C. Compare lengths including spaces only
D. Check only first and last characters ignoring case

Solution

  1. Step 1: Normalize strings by case and spaces

    Convert all letters to lowercase and remove spaces to compare only meaningful characters.
  2. Step 2: Count characters or sort normalized strings

    After normalization, counting characters or sorting will correctly identify anagrams ignoring case and spaces.
  3. Final Answer:

    Convert both to lowercase, remove spaces, then count characters -> Option B
  4. Quick Check:

    Normalize case and spaces before checking [OK]
Hint: Normalize case and remove spaces before checking anagrams [OK]
Common Mistakes:
  • Comparing strings with spaces included
  • Ignoring case differences
  • Assuming length check includes spaces
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard