Files
2026-06-05 18:15:42 -04:00

3.0 KiB

id, title, difficulty, tags, status, date_solved, leetcode_url, review_needed
id title difficulty tags status date_solved leetcode_url review_needed
242 Valid Anagram Easy
hash-table
string
sorting
Solved 2026-06-05 https://leetcode.com/problems/valid-anagram/ false

242. Valid Anagram

[!info] Problem Link: LeetCode - Valid Anagram

📝 Problem Description

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.


📥 Example 1

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

📥 Example 2

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


💡 Approaches & Explanations

Approach 1: Hash Map (Frequency Counter) — Optimal

Since an anagram must have the exact same characters with the same frequencies, we can use a hash map (or a fixed-size array for lowercase English letters) to count the occurrences of each character in both strings.

  1. If the lengths of s and t are different, they cannot be anagrams.
  2. Count the frequency of each character in s.
  3. Decrement the frequency for each character in t.
  4. If all counts return to zero, the strings are anagrams.

📊 Complexity Analysis

  • Time Complexity: \mathcal{O}(N) where N is the length of the strings. We iterate through each string once.
  • Space Complexity: \mathcal{O}(1) because the size of the hash map is limited by the number of unique characters in the alphabet (e.g., 26 for lowercase English letters).

Approach 2: Sorting

If we sort both strings, two anagrams will result in the same identical string.

  • Time Complexity: \mathcal{O}(N \log N) due to sorting.
  • Space Complexity: \mathcal{O}(1) or \mathcal{O}(N) depending on whether the language allows in-place string sorting or requires converting the string to a list.

💻 Code Implementations

Python3

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        
        count = {}
        for char in s:
            count[char] = count.get(char, 0) + 1
        
        for char in t:
            if char not in count or count[char] == 0:
                return False
            count[char] -= 1
            
        return True

# Alternative using collections.Counter
from collections import Counter
class Solution2:
    def isAnagram(self, s: str, t: str) -> bool:
        return Counter(s) == Counter(t)

🧠 Key Takeaways & Lessons

  • Character Counting: For problems involving permutations or character frequency, a hash map or an array of size 26 is often the most efficient tool.
  • Early Exit: Always check for length differences first to save time in edge cases.
  • Sorting as a Normalization: Sorting is a powerful way to "normalize" data to check for equivalence in different orderings, though it is often slightly less efficient than counting.