Code Logo

Valid Anagram

Published at16 Mar 2026
Easy 9 views
Like0

You are given two strings and need to decide whether one is an anagram of the other.

That means they must contain exactly the same characters with exactly the same counts. The order does not matter, but the frequency does. If one string has an extra letter or is missing a copy of some letter, the answer is false.

For example, s = "anagram" and t = "nagaram" return true because both strings use the same letters the same number of times. But s = "rat" and t = "car" return false because the letters do not match.

So the task is to compare the full character inventory of both strings, not their order.

Example Input & Output

Example 1
Input
s = "anagram", t = "nagaram"
Output
true
Explanation

Both strings contain the same letters with the same counts.

Example 2
Input
s = "rat", t = "car"
Output
false
Explanation

The letters do not match.

Example 3
Input
s = "aacc", t = "ccac"
Output
false
Explanation

The character counts are different.

Algorithm Flow

Recommendation Algorithm Flow for Valid Anagram
Recommendation Algorithm Flow for Valid Anagram

Solution Approach

A frequency map is the most direct solution.

First, if the two strings have different lengths, you can return false immediately. Otherwise count the characters in one string, then subtract counts using the other string.

If any character count drops below zero, or if the final counts are not all zero, the strings are not anagrams. If everything balances exactly, return true.

This takes O(n) time and uses O(k) extra space for the distinct characters.

Best Answers

java
import java.util.*;
class Solution {
    public boolean valid_anagram(String s, String t) {
        if (s.length() != t.length()) return false;
        Map<Character, Integer> count = new HashMap<>();
        for (char ch : s.toCharArray()) count.put(ch, count.getOrDefault(ch, 0) + 1);
        for (char ch : t.toCharArray()) {
            if (!count.containsKey(ch) || count.get(ch) == 0) return false;
            count.put(ch, count.get(ch) - 1);
        }
        return true;
    }
}