Browse curriculum

Valid Anagram (LeetCode 242)

Valid Anagram (LeetCode 242): decide whether two strings are anagrams by counting letters in a hash map.

Problem Understanding

Valid Anagram: given two strings s and t, return true if t is an anagram of s: the same letters, each used the same number of times, in any order.

Examples: s = "anagram", t = "nagaram" is true. s = "rat", t = "car" is false.

Attempt 1: Sort Both Strings

Sort the letters of both strings and compare: anagrams sort to the same string. It is correct and short, but sorting costs O(n log n) time. The question underneath: does every letter appear the same number of times in both?, can be answered by counting, without ordering anything.

The Intuition: Count, Then Spend

A hash map from letter to count turns the question into bookkeeping:

  1. If the lengths differ, return false immediately.
  2. Walk s and add one to each letter's count.
  3. Walk t and spend one count per letter. If a letter's count is already 0, t has more of that letter than s: return false.

If t finishes without running out of anything, the strings are anagrams. The length check is what makes that last step safe: equal lengths and nothing overspent means every count ended at exactly 0.

Valid Anagram Visualization

s = "anagram", t = "nagaram"

LENGTHS MATCH

s

a

0

n

1

a

2

g

3

r

4

a

5

m

6

t

n

0

a

1

g

2

a

3

r

4

a

5

m

6

Answer

:

count (letter:count)

Empty

 

Both strings have 7 letters. Start an empty count

Next

s[0] = 'a': count['a'] is now 1

Free preview: the first 5 of 16 steps

s

t

Both strings are drawn as rows. The first pass walks s while the count map beside the figure grows; the second walks t while the counts fall and matched letters grey out. A letter of t that finds its count at 0 ends the run.

Valid Anagram Dry Run

Input: s = "rat", t = "car"

Step Letter Action count after
1 - lengths 3 = 3, continue {}
2 s[0] = 'r' count {r: 1}
3 s[1] = 'a' count {r: 1, a: 1}
4 s[2] = 't' count {r: 1, a: 1, t: 1}
5 t[0] = 'c' count['c'] is 0 return false

t asks for a 'c' that s never had.

Valid Anagram LeetCode Solution

Letter counts in a hash map; in C, an array of 26 counts plays the same role.

Valid Anagram Code
1var isAnagram = function(s, t) {
2 if (s.length !== t.length) {
3 return false;
4 }
5 const count = new Map();
6 for (const ch of s) {
7 count.set(ch, (count.get(ch) || 0) + 1);
8 }
9 for (const ch of t) {
10 if (!count.get(ch)) {
11 return false;
12 }
13 count.set(ch, count.get(ch) - 1);
14 }
15 return true;
16};

Valid Anagram in Python, Java, C++, TypeScript and C

Valid Anagram in Python
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        count = {}
        for ch in s:
            count[ch] = count.get(ch, 0) + 1
        for ch in t:
            if count.get(ch, 0) == 0:
                return False
            count[ch] -= 1
        return True
Valid Anagram in Java
class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        Map<Character, Integer> count = new HashMap<>();
        for (char ch : s.toCharArray()) {
            count.merge(ch, 1, Integer::sum);
        }
        for (char ch : t.toCharArray()) {
            if (count.getOrDefault(ch, 0) == 0) {
                return false;
            }
            count.merge(ch, -1, Integer::sum);
        }
        return true;
    }
}
Valid Anagram in C++
class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) {
            return false;
        }
        unordered_map<char, int> count;
        for (char ch : s) {
            count[ch]++;
        }
        for (char ch : t) {
            if (count[ch] == 0) {
                return false;
            }
            count[ch]--;
        }
        return true;
    }
};
Valid Anagram in TypeScript
function isAnagram(s: string, t: string): boolean {
    if (s.length !== t.length) {
        return false;
    }
    const count = new Map<string, number>();
    for (const ch of s) {
        count.set(ch, (count.get(ch) ?? 0) + 1);
    }
    for (const ch of t) {
        if (!count.get(ch)) {
            return false;
        }
        count.set(ch, count.get(ch)! - 1);
    }
    return true;
}
Valid Anagram in C
bool isAnagram(char* s, char* t) {
    if (strlen(s) != strlen(t)) {
        return false;
    }
    int count[26] = {0}; // s and t are lowercase English letters
    for (char *p = s; *p; p++) {
        count[*p - 'a']++;
    }
    for (char *p = t; *p; p++) {
        if (count[*p - 'a'] == 0) {
            return false;
        }
        count[*p - 'a']--;
    }
    return true;
}

Edge Cases & Common Mistakes

  • Different lengths: return false before counting anything.
  • Same letters, different amounts ("aab", "abb"): the second 'b' of t finds its count at 0.
  • Skipping the length check: "ab" and "abc" would then need a final scan for leftover counts: the check removes that scan.
  • Unicode input: the hash map version works for any characters; the 26-slot array only for lowercase English letters.

Summary

Counting with a hash map replaces sorting: build the counts from one string, spend them on the other, and stop the moment something runs out. The same frequency map, keyed differently, is the heart of Group Anagrams.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Compare lengths

    If s and t have different lengths, return false.

  2. Count s

    Add one to the count of each letter of s.

  3. Spend on t

    For each letter of t, return false if its count is 0; otherwise subtract one. Return true at the end.

Frequently asked questions

How do you check if two strings are anagrams?

If the lengths differ they are not. Otherwise count each letter of s in a hash map, then walk t and spend one count per letter; if any letter of t finds its count at 0, they are not anagrams. If t finishes, they are.


Why not sort both strings and compare them?

Sorting works and is short to write, but it costs O(n log n) time. Counting letters is O(n) time with O(k) extra space for k distinct letters: O(1) when the alphabet is fixed, such as 26 lowercase letters.


Why check the lengths first?

Strings of different lengths can never be anagrams, so the check returns early. It also makes the final step valid: with equal lengths, if no letter of t ever runs out, every count must end at exactly 0.

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description