242. Valid Anagram¶
Edited by Charles
Easy · Python · HashTable
Problem
Read the original problem on LeetCode.
The official page contains the problem statement, examples, and constraints.
Explanation, examples & other approaches
Core idea
Main idea: make two sets of counts of each character in s and t. Compare these two sets if they are the same. Remember the one-liner.
Original study notes follow, including intermediate snippets and earlier attempts.
- Main idea: make two sets of counts of each character in s and t. Compare these two sets if they are the same.
- Remember the one-liner.
- Remember the string’s built-in method count(), s.count(char).
Study record
| Field | Value |
|---|---|
| Attempts | 2 |
| Mastery | ❚❚ |
| The Latest Attempt | January 5, 2026 |
Python solution¶
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# set() is needed for the time complexity
s_set = {char: s.count(char) for char in set(s)}
t_set = {char: t.count(char) for char in set(t)}
if s_set != t_set:
return False
return True