Skip to content

Commit 032d633

Browse files
authored
Merge pull request #63 from AbdulWahab938/feature/valid-anagram
Solution #242 - Abdul Wahab - 14/07/2025
2 parents 72c1e92 + 248d36d commit 032d633

File tree

4 files changed

+196
-0
lines changed

4 files changed

+196
-0
lines changed
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
# 242. Valid Anagrams
2+
3+
**Difficulty:** Easy
4+
**Category:** Strings, Hashing, Sorting
5+
**Leetcode Link:** [Problem Link](https://leetcode.com/problems/valid-anagram/)
6+
7+
---
8+
9+
## 📝 Introduction
10+
11+
Given two strings, determine whether they are anagrams of each other.
12+
Two strings are anagrams if they contain the same characters with the same frequencies, regardless of the order.
13+
14+
### Constraints:
15+
- Only uppercase letters (e.g., 'A' to 'Z') are considered.
16+
- Strings must be the same length to qualify as anagrams.
17+
- Output `true` if they are anagrams, otherwise `false`.
18+
19+
---
20+
21+
## 💡 Approach & Key Insights
22+
23+
- The core idea is to check whether the two strings contain the exact same characters with the same counts.
24+
- If their lengths differ, they can't be anagrams.
25+
- There are multiple valid ways to compare character distributions:
26+
- Sort and compare
27+
- Count frequencies using a fixed-size array (best for character sets of known size)
28+
29+
---
30+
31+
## 🛠️ Breakdown of Approaches
32+
33+
### 1️⃣ Brute Force / Naive Approach — Sorting
34+
35+
- **Explanation:**
36+
Sort both strings and check if they are equal. If sorted versions are identical, then the strings are anagrams.
37+
38+
- **Time Complexity:** O(N log N) – Due to sorting of both strings.
39+
- **Space Complexity:** O(1) – Assuming in-place sorting.
40+
41+
- **Example/Dry Run:**
42+
43+
```plaintext
44+
Input: str1 = "INTEGER", str2 = "TEGERNI"
45+
Step 1: Sort str1 → "EEGINRT"
46+
Step 2: Sort str2 → "EEGINRT"
47+
Step 3: Compare both → Equal → return true
48+
49+
Output: true
50+
```
51+
52+
---
53+
54+
### 2️⃣ Optimized Approach — Frequency Count
55+
56+
- **Explanation:**
57+
Use a frequency array of size 26 (for uppercase letters).
58+
- Increment count for characters in str1
59+
- Decrement for characters in str2
60+
- If all frequencies are 0 in the end → anagrams
61+
62+
- **Time Complexity:** O(N) – One pass for each string.
63+
- **Space Complexity:** O(1) – Fixed array size of 26.
64+
65+
- **Example/Dry Run:**
66+
67+
```plaintext
68+
Input: str1 = "INTEGER", str2 = "TEGERNI"
69+
Step 1: freq[] = [0,...,0]
70+
71+
Step 2: For str1 →
72+
I+1, N+1, T+1, E+1, G+1, E+1, R+1
73+
→ freq = {G:1, E:2, I:1, N:1, R:1, T:1}
74+
75+
Step 3: For str2 →
76+
T-1, E-1, G-1, E-1, R-1, N-1, I-1
77+
→ freq = all zero
78+
79+
Step 4: All frequencies are zero → return true
80+
81+
Output: true
82+
```
83+
84+
---
85+
86+
### 3️⃣ Best / Final Optimized Approach
87+
88+
- **Explanation:**
89+
Frequency counting is optimal for limited character sets (like uppercase/lowercase letters).
90+
- No sorting
91+
- No additional data structures like maps or sets
92+
- Linear time and constant space
93+
94+
- **Time Complexity:** O(N)
95+
- **Space Complexity:** O(1)
96+
97+
---
98+
99+
## 📊 Complexity Analysis
100+
101+
| Approach | Time Complexity | Space Complexity |
102+
| ------------- | --------------- | ---------------- |
103+
| Brute Force | O(N log N) | O(1) |
104+
| Optimized | O(N) | O(1) |
105+
| Best Approach | O(N) | O(1) |
106+
107+
---
108+
109+
## 📉 Optimization Ideas
110+
111+
- Convert both strings to the same case (e.g., uppercase) to make comparison case-insensitive if needed.
112+
- If dealing with Unicode characters, use a `HashMap` instead of fixed-size array.
113+
- Early termination: While building the frequency array, if any count goes negative, return `false` early.
114+
115+
---
116+
117+
## 📌 Example Walkthroughs & Dry Runs
118+
119+
```plaintext
120+
Example 1:
121+
Input: str1 = "CAT", str2 = "ACT"
122+
123+
Step 1: freq[26] = {0}
124+
Step 2: +1 for C, A, T → freq[C]=1, A=1, T=1
125+
Step 3: -1 for A, C, T → all become 0
126+
Output: true
127+
128+
Example 2:
129+
Input: str1 = "RULES", str2 = "LESRT"
130+
131+
Step 1: freq[26] = {0}
132+
Step 2: +1 for R, U, L, E, S → freq[R]=1, U=1, L=1, E=1, S=1
133+
Step 3: -1 for L, E, S, R, T → freq[T]=-1 (unexpected char)
134+
Output: false
135+
```
136+
137+
---
138+
139+
## 🔗 Additional Resources
140+
141+
- [GeeksforGeeks – Anagram Check](https://www.geeksforgeeks.org/check-whether-two-strings-are-anagram-of-each-other/)
142+
143+
---
144+
145+
Author: Abdul Wahab
146+
Date: 19/07/2025
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public:
3+
bool isAnagram(string s, string t) {
4+
if (s.length() != t.length())
5+
return false;
6+
int freq[26] = {0};
7+
for (int i = 0; i < s.length(); i++) {
8+
freq[s[i] - 'a']++;
9+
}
10+
for (int i = 0; i < t.length(); i++) {
11+
freq[t[i] - 'a']--;
12+
}
13+
for (int i = 0; i < 26; i++) {
14+
if (freq[i] != 0)
15+
return false;
16+
}
17+
return true;
18+
}
19+
};
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public boolean isAnagram(String s, String t) {
3+
if (s.length() != t.length())
4+
return false;
5+
int[] freq = new int[26];
6+
for (int i = 0; i < s.length(); i++) {
7+
freq[s.charAt(i) - 'a']++;
8+
}
9+
for (int i = 0; i < t.length(); i++) {
10+
freq[t.charAt(i) - 'a']--;
11+
}
12+
for (int i = 0; i < 26; i++) {
13+
if (freq[i] != 0)
14+
return false;
15+
}
16+
return true;
17+
}
18+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def isAnagram(self, s: str, t: str) -> bool:
3+
if len(s) != len(t):
4+
return False
5+
freq = [0] * 26
6+
for ch in s:
7+
freq[ord(ch) - ord('a')] += 1
8+
for ch in t:
9+
freq[ord(ch) - ord('a')] -= 1
10+
for val in freq:
11+
if val != 0:
12+
return False
13+
return True

0 commit comments

Comments
 (0)