Check if Two Strings Are Anagrams in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include<stdio.h>
#include<string.h>
int main() {
    char a[100], b[100]; int f[26]={0};
    scanf("%s%s", a, b);
    if(strlen(a)!=strlen(b)) return printf("Not Anagram");
    for(int i=0; a[i]; i++) f[a[i]-'a']++, f[b[i]-'a']--;
    for(int i=0; i<26; i++) if(f[i]) return printf("Not Anagram");
    printf("Anagram");
}

C Output

Input:  
listen  
silent  

Output:  
Anagram


C++ Program

#include<iostream>
using namespace std;

int main() {
    string a, b; cin >> a >> b;
    int f[26] = {0};
    if(a.size() != b.size()) return cout << "Not Anagram", 0;
    for(int i=0; i<a.size(); i++) f[a[i]-'a']++, f[b[i]-'a']--;
    for(int i=0; i<26; i++) if(f[i]) return cout << "Not Anagram", 0;
    cout << "Anagram";
}

C++ Output

Input:  
race  
care  

Output:  
Anagram


JAVA Program

import java.util.*;

class A {
    public static void main(String[] x) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next(), b = sc.next();
        if(a.length() != b.length()) { System.out.print("Not Anagram"); return; }
        int[] f = new int[26];
        for(int i=0; i<a.length(); i++) {
            f[a.charAt(i)-'a']++;
            f[b.charAt(i)-'a']--;
        }
        for(int i : f) if(i != 0) { System.out.print("Not Anagram"); return; }
        System.out.print("Anagram");
    }
}

JAVA Output

Input:  
god  
dog  

Output:  
Anagram


Python Program

a, b = input(), input()
print("Anagram" if sorted(a)==sorted(b) else "Not Anagram")

Python Output

Input:  
heart  
earth  

Output:  
Anagram


In-Depth Learning – Whole Concept in Paragraphs
What Is an Anagram?
An anagram is a rearrangement of letters of one string to create another. For instance, "listen" and "silent" are anagrams as both have the same letters: l, i, s, t, e, n.

The key thing is: both strings need to:

Be the same length

Have the same characters

Have those characters occurring in the same frequency

If there is one letter too many, one missing, or one repeated differently — they're not anagrams.

How the Code Works
All flavors (C, C++, Java):

Accept two strings as input.

If they have different lengths → they are not anagrams.

Employ a frequency array of length 26 (for lower case letters).

For each character in string a, increment the same index.

For each character in string b, decrement the same index.

If all values in the array are zero at the end → strings are anagrams.

Python employs the simplest logic:

Sort both strings with sorted()

If the sorted outputs are equal → they are anagrams.

This method is valid for lowercase letters, and can be made case-insensitive or unicode-aware if necessary.

Example
Input: "triangle" and "integral"

Sorted:

"triangle" → a, e, g, i, l, n, r, t

"integral" → a, e, g, i, l, n, r, t

✅ Match → They're anagrams.

Real-Life Analogy
Anagrams are like rearranging the fridge magnets to spell other words using the same group of letters. If two individuals are presented with the same group of magnetic letters, and one forms "stop" while another forms "pots", they've made anagrams — using nothing more, nothing less, than what they were given.

Another comparison is puzzles — two individuals provided with the same puzzle pieces should be able to create the same image, even though the pieces are arranged differently.

Where and When Is It Used?
Anagram detection is essential in:

Cryptography and password analysis

Spell checkers and autocorrect mechanisms

Interview questions (extremely popular)

Word games and language assistants

Search engine optimization (SEO) for content variation

Plagiarism detection when scanning rearranged phrases

In interviews, it's usually paired with hashing, dictionaries, or sorting ability.

Time and Space Complexity
Approach Time_Space
Using Sorting O(n log n) O(n)
Using Frequency Array (Optimal) O(n) O(1) for fixed-size 26 array

Using sorting is easier but slower. Using frequency count is faster and more efficient for fixed character sets.

Python-Specific Tip
For case-insensitive comparison:

python

a, b = input().lower(), input().lower()
print("Anagram" if sorted(a)==sorted(b) else "Not Anagram")
Or use collections.Counter:


from collections import Counter
print("Anagram" if Counter(a)==Counter(b) else "Not Anagram")
This tallies frequency explicitly and accommodates all characters.

SEO-Optimized Natural Paragraph for Ranking
Need to test whether two strings are anagrams in C, C++, Java, or Python? This tutorial offers the shortest and most efficient code to crack one of the most popular string puzzles in coding interviews. Anagrams are strings comprising identical characters used in various orders. This guide covers anagram logic using frequency arrays, sorting, and hash maps across all languages. You’ll learn the mathematical and logical principles behind string character frequency, how to handle edge cases, and how to implement the most optimized solutions for competitive programming and real-world applications.