Valid Anagram
LeetCode 242 · Easy · solution, intuition & step-by-step walkthrough
One frequency table: +1 for s, −1 for t, all zeros at the end.
This is how I solved Valid Anagram (LeetCode 242), an easy problem from the Hashing / Anagram pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Two strings are anagrams when every letter appears the same number of times in both. Count letters of s up and letters of t down in one 26-slot table; if every slot ends at zero, the counts match.
Approach
- 1
Different lengths can't be anagrams.
- 2
Map each letter to an index 0–25 with ord(c) − ord('a').
- 3
Increment for s[i], decrement for t[i] in the same loop.
- 4
Return True if every count is zero.
How I solved it
Frequency tablePythonO(n) time · O(1) space
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s)!=len(t):
return False
n = len(s)
freq_table = [0]*26
for i in range(n):
char1 = s[i]
char2 = t[i]
"""
ord(a) = 97
ord(b) = 98
ord('a') - ord('a') =0
ord('b') - ord('a') = 1
ord('c') - ord('a') = 2
"""
freq_table[ord(char1)-ord('a')]+=1
freq_table[ord(char2)-ord('a')]-=1
return all(x==0 for x in freq_table)Valid Anagram — FAQ
What is the intuition behind Valid Anagram?
Two strings are anagrams when every letter appears the same number of times in both. Count letters of s up and letters of t down in one 26-slot table; if every slot ends at zero, the counts match.
How do you solve Valid Anagram (LeetCode 242)?
1. Different lengths can't be anagrams. 2. Map each letter to an index 0–25 with ord(c) − ord('a'). 3. Increment for s[i], decrement for t[i] in the same loop. 4. Return True if every count is zero.
What is the time and space complexity of Valid Anagram?
Time: O(n). Space: O(1) — 26 counters. (Accepted approach: Frequency table.)
What are common mistakes in Valid Anagram?
Unicode input would need a dict instead of a fixed 26-slot array.