← Back to Leo Academy Masterclass

Problem #242: Valid Anagram

Easy Hashmap

Intuition & Strategy Breakdown

Count character frequencies using a fixed size array of 26 integers. Increment for s, decrement for t; return true if all counts are zero.

Python Solution

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t): return False
        return collections.Counter(s) == collections.Counter(t)

Java Solution

class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;
        int[] counts = new int[26];
        for (int i = 0; i < s.length(); i++) {
            counts[s.charAt(i) - 'a']++;
            counts[t.charAt(i) - 'a']--;
        }
        for (int count : counts) {
            if (count != 0) return false;
        }
        return true;
    }
}
Watch Interactive Video on Leo Academy Main App