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
Both strings contain the same letters with the same counts.
The letters do not match.
The character counts are different.
Algorithm Flow

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
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
