← Back to DSA Course | Chapter 3: Strings | Lesson 4 of 6

Anagram और Frequency Count

Anagrams letter tiles के दो bags जैसे हैं जिनमें बिल्कुल वही tiles हैं, सिर्फ अलग arrange किए गए। हर letter की कितनी हैं यह count करना बताता है कि वे match करते हैं या नहीं।
Syntax
markup
freq = {}
for ch in text:
    freq[ch] = freq.get(ch, 0) + 1

is_anagram = freq1 == freq2

Anagram Basics

दो strings एक-दूसरे के anagrams हैं अगर उनमें बिल्कुल वही characters बिल्कुल वही frequencies के साथ हैं, बस rearranged, जैसे listen और silent। characters के उसी multiset की अलग orderings ही उन्हें anagrams बनाती हैं।

उदाहरण: Anagram Basics

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    string a = "listen", b = "silent";
    string sa = a, sb = b;
    sort(sa.begin(), sa.end()); sort(sb.begin(), sb.end());
    cout << (sa == sb ? "Anagrams" : "Not anagrams") << endl;
    return 0;
}
import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        char[] a = "listen".toCharArray(), b = "silent".toCharArray();
        Arrays.sort(a); Arrays.sort(b);
        System.out.println(Arrays.equals(a, b) ? "Anagrams" : "Not anagrams");
    }
}
a, b = "listen", "silent"
print("Anagrams" if sorted(a) == sorted(b) else "Not anagrams")
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) { return *(char*)a - *(char*)b; }
int main() {
    char a[] = "listen", b[] = "silent";
    qsort(a, strlen(a), 1, cmp);
    qsort(b, strlen(b), 1, cmp);
    printf("%s\n", strcmp(a, b) == 0 ? "Anagrams" : "Not anagrams");
    return 0;
}

Frequency Count

Frequency का मतलब बस यह count करना है कि किसी string में हर distinct character कितनी बार दिखता है, जो order की परवाह किए बिना दो strings को anagram relationship के लिए compare करने के लिए चाहिए key जानकारी है।

उदाहरण: Frequency Count

#include <iostream>
#include <map>
using namespace std;
int main() {
    string s = "banana";
    map<char, int> freq;
    for (char c : s) freq[c]++;
    for (auto& p : freq) cout << p.first << ": " << p.second << endl;
    return 0;
}
import java.util.TreeMap;
public class Main {
    public static void main(String[] args) {
        String s = "banana";
        TreeMap<Character, Integer> freq = new TreeMap<>();
        for (char c : s.toCharArray()) freq.put(c, freq.getOrDefault(c, 0) + 1);
        for (var e : freq.entrySet()) System.out.println(e.getKey() + ": " + e.getValue());
    }
}
s = "banana"
freq = {}
for c in s:
    freq[c] = freq.get(c, 0) + 1
for c, n in sorted(freq.items()):
    print(f"{c}: {n}")
#include <stdio.h>
#include <string.h>
int main() {
    char s[] = "banana";
    int freq[26] = {0};
    for (int i = 0; i < strlen(s); i++) freq[s[i] - 'a']++;
    for (int i = 0; i < 26; i++) if (freq[i]) printf("%c: %d\n", 'a' + i, freq[i]);
    return 0;
}

Frequency Array

जब character set limited हो, जैसे lowercase English letters, 26 counters (प्रति letter एक) का एक fixed-size array alphabet के सापेक्ष O(1) space में frequencies track कर सकता है, counting को बेहद तेज़ बनाते हुए।

उदाहरण: Frequency Array

#include <iostream>
using namespace std;
int main() {
    string s = "hello world";
    int freq[26] = {0};
    for (char c : s) if (c >= 'a' && c <= 'z') freq[c - 'a']++;
    cout << "'l' count: " << freq['l' - 'a'] << endl;
    return 0;
}
public class Main {
    public static void main(String[] args) {
        String s = "hello world";
        int[] freq = new int[26];
        for (char c : s.toCharArray()) if (c >= 'a' && c <= 'z') freq[c - 'a']++;
        System.out.println("'l' count: " + freq['l' - 'a']);
    }
}
s = "hello world"
freq = [0] * 26
for c in s:
    if 'a' <= c <= 'z':
        freq[ord(c) - ord('a')] += 1
print("'l' count:", freq[ord('l') - ord('a')])
#include <stdio.h>
#include <string.h>
int main() {
    char s[] = "hello world";
    int freq[26] = {0};
    for (int i = 0; i < strlen(s); i++) if (s[i] >= 'a' && s[i] <= 'z') freq[s[i] - 'a']++;
    printf("'l' count: %d\n", freq['l' - 'a']);
    return 0;
}

Anagram Using Frequency

Frequency arrays उपयोग करके यह जांचने के लिए कि दो strings anagrams हैं या नहीं, दोनों strings को अलग arrays में count करें (या एक string के लिए increment करें और दूसरी के लिए decrement करें) और confirm करें कि सभी counts zero पर खत्म होते हैं, जो O(n) time में चलता है।

उदाहरण: Anagram Using Frequency

#include <iostream>
using namespace std;
int main() {
    string a = "anagram", b = "nagaram";
    int freq[26] = {0};
    for (char c : a) freq[c - 'a']++;
    for (char c : b) freq[c - 'a']--;
    bool isAnagram = true;
    for (int i = 0; i < 26; i++) if (freq[i] != 0) isAnagram = false;
    cout << (isAnagram ? "Anagrams" : "Not anagrams") << endl;
    return 0;
}
public class Main {
    public static void main(String[] args) {
        String a = "anagram", b = "nagaram";
        int[] freq = new int[26];
        for (char c : a.toCharArray()) freq[c - 'a']++;
        for (char c : b.toCharArray()) freq[c - 'a']--;
        boolean isAnagram = true;
        for (int f : freq) if (f != 0) isAnagram = false;
        System.out.println(isAnagram ? "Anagrams" : "Not anagrams");
    }
}
a, b = "anagram", "nagaram"
freq = [0] * 26
for c in a:
    freq[ord(c) - ord('a')] += 1
for c in b:
    freq[ord(c) - ord('a')] -= 1
print("Anagrams" if all(f == 0 for f in freq) else "Not anagrams")
#include <stdio.h>
#include <string.h>
int main() {
    char a[] = "anagram", b[] = "nagaram";
    int freq[26] = {0}, isAnagram = 1;
    for (int i = 0; i < strlen(a); i++) freq[a[i] - 'a']++;
    for (int i = 0; i < strlen(b); i++) freq[b[i] - 'a']--;
    for (int i = 0; i < 26; i++) if (freq[i] != 0) isAnagram = 0;
    printf("%s\n", isAnagram ? "Anagrams" : "Not anagrams");
    return 0;
}

Frequency Practice

Frequency counting anagrams से आगे भी लगातार दिखता है, सबसे common character ढूंढना, duplicates detect करना, और एक-दूसरे के anagrams वाले words group करना सहित, इसलिए इसे पहले plain words पर practice करना worth है।

उदाहरण: Frequency Practice

#include <iostream>
using namespace std;
int main() {
    string s = "programming";
    int freq[26] = {0};
    for (char c : s) freq[c - 'a']++;
    int best = 0;
    for (int i = 1; i < 26; i++) if (freq[i] > freq[best]) best = i;
    cout << "Most common: '" << (char)('a' + best) << "' (" << freq[best] << " times)" << endl;
    return 0;
}
public class Main {
    public static void main(String[] args) {
        String s = "programming";
        int[] freq = new int[26];
        for (char c : s.toCharArray()) freq[c - 'a']++;
        int best = 0;
        for (int i = 1; i < 26; i++) if (freq[i] > freq[best]) best = i;
        System.out.println("Most common: '" + (char) ('a' + best) + "' (" + freq[best] + " times)");
    }
}
s = "programming"
freq = [0] * 26
for c in s:
    freq[ord(c) - ord('a')] += 1
best = freq.index(max(freq))
print(f"Most common: '{chr(ord('a') + best)}' ({freq[best]} times)")
#include <stdio.h>
#include <string.h>
int main() {
    char s[] = "programming";
    int freq[26] = {0};
    for (int i = 0; i < strlen(s); i++) freq[s[i] - 'a']++;
    int best = 0;
    for (int i = 1; i < 26; i++) if (freq[i] > freq[best]) best = i;
    printf("Most common: '%c' (%d times)\n", 'a' + best, freq[best]);
    return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. 26 size का array उन characters के साथ उपयोग करना जो lowercase letters नहीं हैं, इसलिए s[i] - a एक negative या huge index देता है।
  2. सिर्फ यह जांचना कि दोनों strings में वही letters हैं, वही counts नहीं, इसलिए "aab" और "abb" anagrams जैसे दिखते हैं।
  3. पहले lengths compare करना भूल जाना, जब अलग lengths कभी anagrams नहीं हो सकतीं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.