Skip to content

Commit 8814860

Browse files
Add explanation and solution for LeetCode problem 242 (Valid Anagram)
1 parent ad2075f commit 8814860

File tree

2 files changed

+140
-0
lines changed

2 files changed

+140
-0
lines changed

explanations/242/en.md

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
## 242. Valid Anagram [Easy]
2+
3+
https://leetcode.com/problems/valid-anagram
4+
5+
## Description
6+
Given two strings `s` and `t`, return `true` if `t` is an [anagram](https://en.wikipedia.org/wiki/Anagram) of `s`, and `false` otherwise.
7+
8+
**Examples**
9+
10+
```tex
11+
Example 1:
12+
Input: s = "anagram", t = "nagaram"
13+
Output: true
14+
15+
Example 2:
16+
Input: s = "rat", t = "car"
17+
Output: false
18+
```
19+
20+
**Constraints**
21+
```tex
22+
- 1 <= s.length, t.length <= 5 * 10^4
23+
- s and t consist of lowercase English letters
24+
```
25+
26+
**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
27+
28+
## Explanation
29+
30+
### Strategy
31+
Let's restate the problem: You're given two strings, and you need to determine if one is an anagram of the other. An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once.
32+
33+
This is a **character counting problem** that can be solved using hash tables to track the frequency of each character in both strings.
34+
35+
**What is given?** Two strings `s` and `t` of potentially different lengths.
36+
37+
**What is being asked?** Determine if `t` is an anagram of `s`.
38+
39+
**Constraints:** The strings can be up to 50,000 characters long and contain only lowercase English letters.
40+
41+
**Edge cases:**
42+
- Strings of different lengths
43+
- Empty strings
44+
- Strings with repeated characters
45+
- Strings with all identical characters
46+
47+
**High-level approach:**
48+
The solution involves counting the frequency of each character in both strings and comparing them. If the character counts match exactly, the strings are anagrams.
49+
50+
**Decomposition:**
51+
1. **Check length equality**: If strings have different lengths, they can't be anagrams
52+
2. **Count characters in first string**: Use a hash table to track character frequencies
53+
3. **Decrement counts for second string**: For each character in the second string, decrement its count
54+
4. **Verify all counts are zero**: If any count is not zero, the strings are not anagrams
55+
56+
**Brute force vs. optimized strategy:**
57+
- **Brute force**: Try all possible permutations of one string. This takes O(n!) time.
58+
- **Optimized**: Use character counting with hash tables. This takes O(n) time.
59+
60+
### Steps
61+
Let's walk through the solution step by step using the first example: `s = "anagram"`, `t = "nagaram"`
62+
63+
**Step 1: Check string lengths**
64+
- `s.length = 7`, `t.length = 7`
65+
- Lengths match ✓
66+
67+
**Step 2: Initialize character count dictionary**
68+
- `char_count = {}`
69+
70+
**Step 3: Count characters in first string (s)**
71+
- `s = "anagram"`
72+
- `char_count['a'] = 3` (appears 3 times)
73+
- `char_count['n'] = 1` (appears 1 time)
74+
- `char_count['g'] = 1` (appears 1 time)
75+
- `char_count['r'] = 1` (appears 1 time)
76+
- `char_count['m'] = 1` (appears 1 time)
77+
78+
**Step 4: Decrement counts for second string (t)**
79+
- `t = "nagaram"`
80+
- `t[0] = 'n'`: `char_count['n'] = 1 - 1 = 0`
81+
- `t[1] = 'a'`: `char_count['a'] = 3 - 1 = 2`
82+
- `t[2] = 'g'`: `char_count['g'] = 1 - 1 = 0`
83+
- `t[3] = 'a'`: `char_count['a'] = 2 - 1 = 1`
84+
- `t[4] = 'r'`: `char_count['r'] = 1 - 1 = 0`
85+
- `t[5] = 'a'`: `char_count['a'] = 1 - 1 = 0`
86+
- `t[6] = 'm'`: `char_count['m'] = 1 - 1 = 0`
87+
88+
**Step 5: Verify all counts are zero**
89+
- All character counts are now 0
90+
- The strings are anagrams: `true`
91+
92+
**Why this works:**
93+
By counting characters in the first string and then decrementing for the second string, we ensure that:
94+
1. Both strings contain the same characters
95+
2. Each character appears the same number of times in both strings
96+
3. The final count of 0 for all characters confirms the anagram property
97+
98+
> **Note:** The key insight is using character frequency counting to verify that both strings contain exactly the same characters with the same frequencies. This is much more efficient than trying to find permutations.
99+
100+
**Time Complexity:** O(n) - we visit each character once in each string
101+
**Space Complexity:** O(k) - where k is the number of unique characters (bounded by the character set size)

solutions/242/01.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
def isAnagram(s, t):
2+
"""
3+
Determine if two strings are anagrams of each other.
4+
5+
Args:
6+
s: str - First string
7+
t: str - Second string
8+
9+
Returns:
10+
bool - True if strings are anagrams, False otherwise
11+
"""
12+
# Check if strings have different lengths
13+
if len(s) != len(t):
14+
return False
15+
16+
# Create character count dictionary
17+
char_count = {}
18+
19+
# Count characters in first string
20+
for char in s:
21+
char_count[char] = char_count.get(char, 0) + 1
22+
23+
# Decrement counts for characters in second string
24+
for char in t:
25+
if char not in char_count:
26+
return False
27+
28+
char_count[char] -= 1
29+
30+
# If count becomes negative, strings are not anagrams
31+
if char_count[char] < 0:
32+
return False
33+
34+
# Check if all counts are zero
35+
for count in char_count.values():
36+
if count != 0:
37+
return False
38+
39+
return True

0 commit comments

Comments
 (0)