Skip to main content

Command Palette

Search for a command to run...

anagrams

Published
1 min readView as Markdown
import java.util.HashMap;
import java.util.Map;

public class count_anagram {

    public static int countAnagrams(String txt, String pat) {
        int k = pat.length();
        int count = 0;

        Map<Character, Integer> patMap = new HashMap<>();
        Map<Character, Integer> winMap = new HashMap<>();

        // Step 1: Create frequency map for pattern
        for (char ch : pat.toCharArray()) {
            patMap.put(ch, patMap.getOrDefault(ch, 0) + 1);
        }

        // Step 2: Fill the first window
        for (int i = 0; i < k; i++) {
            char ch = txt.charAt(i);
            winMap.put(ch, winMap.getOrDefault(ch, 0) + 1);
        }

        // Step 3: Compare first window
        if (winMap.equals(patMap)) {
            count++;
        }

        // Step 4: Slide the window
        for (int i = k; i < txt.length(); i++) {
            char newChar = txt.charAt(i);
            char oldChar = txt.charAt(i - k);

            // Add new character
            winMap.put(newChar, winMap.getOrDefault(newChar, 0) + 1);

            // Remove old character
            winMap.put(oldChar, winMap.get(oldChar) - 1);
            if (winMap.get(oldChar) == 0) {
                winMap.remove(oldChar);
            }

            // Compare maps
            if (winMap.equals(patMap)) {
                count++;
            }
        }

        return count;
    }

    public static void main(String[] args) {
        String txt = "forxxorfxdofr";
        String pat = "for";

        int result = countAnagrams(txt, pat);
        System.out.println("Total anagrams found: " + result); // Output: 3
    }
}

More from this blog

Amit singh's blog

235 posts