Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Easy · Free

Count character frequencies with a hash map — anagram detection.

FresherFundamentalsData Structures & Algorithms
Model answer

Frequency map / anagram

java
boolean isAnagram(String s, String t) {
  if (s.length() != t.length()) return false;
  int[] freq = new int[26];
  for (int i = 0; i < s.length(); i++) {
    freq[s.charAt(i) - 'a']++;
    freq[t.charAt(i) - 'a']--;
  }
  for (int c : freq) if (c != 0) return false;
  return true;
}

Count occurrences in O(n) with array (fixed alphabet) or HashMap (Unicode).

Generalize to first unique char and group anagrams.