Bird
Raised Fist0
DSA Cprogramming~10 mins

Anagram Check Techniques in DSA C - Execution Trace

Choose your learning style10 modes available
Concept Flow - Anagram Check Techniques
Input two strings
↓
Check length equal?
No→Return False
Yes↓
Choose technique
↓
Sort both
↓
Compare results
↓
Return True if match, else False
Start by checking if strings have equal length. Then use one of the techniques: sorting, counting characters, or using a hash map to compare. Return true if they match.
Execution Sample
DSA C
bool areAnagrams(char* s1, char* s2) {
  if (strlen(s1) != strlen(s2)) return false;
  int count[256] = {0};
  for (int i = 0; s1[i]; i++) {
    count[(unsigned char)s1[i]]++;
    count[(unsigned char)s2[i]]--;
  }
  for (int i = 0; i < 256; i++) {
    if (count[i] != 0) return false;
  }
  return true;
}
This code checks if two strings are anagrams by counting character frequencies and comparing counts.
Execution Table
StepOperationIndex iCharacter s1[i]Character s2[i]Count Array ChangeCount Array SnapshotResult
1Check length-----Lengths equal, continue
2Initialize count array---All zeros[0,0,0,...0]-
3Process i=00abcount['a']++, count['b']--count['a']=1, count['b']=-1, others=0-
4Process i=11bacount['b']++, count['a']--count['a']=0, count['b']=0, others=0-
5Process i=22cccount['c']++, count['c']--all zeros-
6Check count array---No non-zero valuesall zerosReturn True (anagrams)
7End-----Finished
💡 All counts zero means strings are anagrams; function returns True
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5Final
count['a']01000
count['b']0-1000
count['c']00000
i-012-
Key Moments - 3 Insights
Why do we increment count for s1[i] but decrement for s2[i] in the same loop?
Because we want to balance character counts. Incrementing for s1[i] and decrementing for s2[i] in the same loop helps detect mismatches quickly. See execution_table rows 3-5 where counts cancel out.
What if strings have different lengths?
The function immediately returns false at step 1 in execution_table because anagrams must have equal length.
Why check all counts after the loop instead of during?
Checking after ensures all characters are balanced. During the loop, partial counts may not reflect final state. See execution_table step 6 where final check confirms all zeros.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what is the count value for character 'a'?
A1
B0
C-1
D2
💡 Hint
Check the 'Count Array Snapshot' column at step 4 in execution_table
At which step does the function decide the strings are anagrams?
AStep 3
BStep 5
CStep 6
DStep 7
💡 Hint
Look at the 'Result' column in execution_table for the step returning True
If the strings were 'abc' and 'abd', what would happen at step 5?
ACount for 'c' would be 1 and for 'd' would be -1
BCount for 'c' would be incremented and decremented
CCount array would be all zeros
DFunction would return True immediately
💡 Hint
Think about how counts change when characters differ at the same index
Concept Snapshot
Anagram Check Techniques:
- Check if strings have equal length first
- Use character count array to track frequency differences
- Increment count for s1 chars, decrement for s2 chars
- After processing, if all counts are zero, strings are anagrams
- Returns true if anagrams, false otherwise
Full Transcript
This visualization shows how to check if two strings are anagrams by comparing character counts. First, the code checks if the strings have the same length. If not, it returns false immediately. Then it uses an array to count characters: for each position, it increments the count for the character in the first string and decrements for the character in the second string. After processing all characters, it checks if all counts are zero. If yes, the strings are anagrams and the function returns true. The execution table traces each step, showing how counts change and how the final decision is made.

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