BudiBadu Logo

Valid Anagram

Hash Table Easy 6 views
Like0

This challenge is like checking if you can spell one word using exact letters from another. In Valid Anagram, you’re given two strings, s and t. Return true if t is an anagram of s. You must use every letter from the original word exactly once, just rearranged.

The "secret sauce" is a Frequency Map. First, verify if the two strings are the same length—if not, you can stop! Then, count character appearances in the first string. As you walk through the second, subtract from those counts. If every tally is exactly zero, you have a perfect match! This approach is efficient, giving linear time complexity O(n). It’s the gold standard for string comparison where order doesn't matter, but totals do!

For text and token tasks, be precise with index movement and substring boundaries. Most hidden failures come from partial-match handling and boundary cuts, so keep comparisons explicit and avoid assumptions about implicit separators or formatting not guaranteed by the input contract.

Examples

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 - Budibadu
Recommendation Algorithm Flow for Valid Anagram - Budibadu

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;
    }
}