Valid Anagram
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.
For Unicode strings or case-insensitive anagrams, a general hash map is needed instead of the fixed-size array. The hash map approach works for any character set.
An alternate solution sorts both strings and compares them. If the sorted versions are equal, they are anagrams. This runs in O(n log n) time compared to the hash map approach's O(n), but uses O(1) space (depending on the sorting algorithm).
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 solution(String s, String t) {
if (s.length() != t.length()) return false;
int[] counts = new int[26];
for (char ch : s.toCharArray()) counts[ch - 'a']++;
for (char ch : t.toCharArray()) {
if (--counts[ch - 'a'] < 0) return false;
}
return true;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
