Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An anagram uses the exact same letters with the exact same counts, only arranged in a different order. The usual hash table approach is to count characters from one string, subtract using the other string, and make sure nothing is left unmatched.
Budibadu uses this problem to train frequency-map thinking. Once that clicks, a lot of string and hash table problems become much easier to recognise.
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

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 problem.
