all entries
A-002Day 022026.05.07easyleetcode #242neetcode150

Valid Anagram

#hash-table#string#sorting
leetcode #242 · valid-anagram
01

Problem

· problem
P.002

Valid Anagram

leetcode #242

Determine if two strings contain the same characters with identical frequencies, regardless of their order.

constraints
  • · 1 ≤ s.length, t.length ≤ 5×10⁴
  • · s and t consist of lowercase English letters only
  • · Different lengths cannot be anagrams
// paraphrased summary — see source for full text
examples
example 1input → output
"anagram"
"nagaram"
true
example 2input → output
"rat"
"car"
false
02

Pre-solve

· pre-solve
● 1list shown● 2select● 3reveal
  • Can strings of different lengths be anagrams?
  • If two strings have the same number of distinct characters, are they anagrams?
  • Does the order of characters matter when checking if strings are anagrams?
  • Can the input strings be empty?
  • Are uppercase letters or special characters possible?
  • Can we modify the input strings?
  • Should we return all anagram pairs?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03

Logic Structure

· logic
● 1slots shown● 2pick per slot● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Length Check and Early Exit
if len(s) != len(t):
if len(s) < len(t):
if s != t:
if len(s) == len(t): return False
step 2· Initialize Frequency Maps
countS, countT = {}, {}
count = {}
countS = countT = {}
countS, countT = set(), set()
step 3· Count Characters via Loopnested
countS[s[i]] = 1 + countS.get(s[i], 0)
countS[s[i]] += 1
countS[s[i]] = countS.get(s[i], 1)
if s[i] in countS: countS[s[i]] += 1
else: countS[s[i]] = 1
step 4· Compare Frequency Maps and Return
return countS == countT
return set(countS.keys()) == set(countT.keys())
return len(countS) == len(countT)
return sorted(countS.values()) == sorted(countT.values())
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04

Solve · Trace

· solve
solution.py
1
class Solution:
2
    def isAnagram(self, s: str, t: str) -> bool:
3
        if len(s) != len(t):
4
            return False
5
6
        countS, countT = {}, {}
7
8
        for i in range(len(s)):
9
            countS[s[i]] = 1 + countS.get(s[i], 0)
10
            countT[t[i]] = 1 + countT.get(t[i], 0)
11
        return countS == countT
12
13
    
14
    # easier solution
15
    #return True if sorted(s) == sorted(t) else False
mental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
"anagram"
"nagaram"
true
case 2
"rat"
"car"
false
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.