Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources
Valid Anagram

Valid Anagram

Problem Statement

You’re a word wizard comparing two strings. Are they anagrams—same letters, different order? This easy-level hashing puzzle is a letter-shuffling showdown—use a map to match those characters perfectly!

Example

Input: s = "anagram", t = "nagaram"

Output: true (Same letters rearranged)

Input: s = "rat", t = "car"

Output: false (Different letters)

Input: s = "a", t = "a"

Output: true (Trivial anagram)

Code

Java
Python
JavaScript
public class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;
        Map map = new HashMap<>();
        for (char c : s.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        for (char c : t.toCharArray()) {
            if (!map.containsKey(c) || map.get(c) == 0) return false;
            map.put(c, map.get(c) - 1);
        }
        return true;
    }
}
            
from collections import Counter
def is_anagram(s, t):
    return Counter(s) == Counter(t)
            
function isAnagram(s, t) {
    if (s.length !== t.length) return false;
    let map = new Map();
    for (let char of s) {
        map.set(char, (map.get(char) || 0) + 1);
    }
    for (let char of t) {
        if (!map.has(char) || map.get(char) === 0) return false;
        map.set(char, map.get(char) - 1);
    }
    return true;
}
            

Explanation

  • Hashing Insight: Count characters in both strings; they must match exactly.
  • Flow: Build a frequency map for s, then subtract t’s counts—mismatch means no anagram.
  • Example Walkthrough: "anagram" → map={a:3,n:1,g:1,r:1,m:1}, "nagaram" matches.
  • Python Magic: Counter comparison is clean and efficient.
  • Edge Case: Different lengths or extra chars (e.g., "a" vs "ab") fail fast.

Note

Time complexity: O(n), Space complexity: O(k) where k is charset size. A hashing spell for wordplay wizards!