Concept Flow - Anagram Check Techniques
Input two strings
Choose technique
Sort both
Compare
Result: True/False
Start with two strings, pick a method: sort and compare or count characters and compare counts, then decide if they are anagrams.
function areAnagrams(s1: string, s2: string): boolean {
if (s1.length !== s2.length) return false;
const count: Record<string, number> = {};
for (const char of s1) count[char] = (count[char] || 0) + 1;
for (const char of s2) {
if (!count[char]) return false;
count[char]--;
}
return true;
}| Step | Operation | Character Processed | Count Map State | Action | Result |
|---|---|---|---|---|---|
| 1 | Check length | - | - | Lengths equal (4 == 4) | Continue |
| 2 | Count chars in s1 | a | {"a":1} | Add 'a' count | - |
| 3 | Count chars in s1 | r | {"a":1,"r":1} | Add 'r' count | - |
| 4 | Count chars in s1 | t | {"a":1,"r":1,"t":1} | Add 't' count | - |
| 5 | Count chars in s1 | s | {"a":1,"r":1,"t":1,"s":1} | Add 's' count | - |
| 6 | Subtract chars in s2 | t | {"a":1,"r":1,"t":0,"s":1} | Subtract 't' count | - |
| 7 | Subtract chars in s2 | a | {"a":0,"r":1,"t":0,"s":1} | Subtract 'a' count | - |
| 8 | Subtract chars in s2 | r | {"a":0,"r":0,"t":0,"s":1} | Subtract 'r' count | - |
| 9 | Subtract chars in s2 | s | {"a":0,"r":0,"t":0,"s":0} | Subtract 's' count | - |
| 10 | Check counts | - | {"a":0,"r":0,"t":0,"s":0} | All zero counts | Return true |
| Variable | Start | After Step 2 | After Step 5 | After Step 9 | Final |
|---|---|---|---|---|---|
| count | {} | {"a":1} | {"a":1,"r":1,"t":1,"s":1} | {"a":0,"r":0,"t":0,"s":0} | {"a":0,"r":0,"t":0,"s":0} |
| s1.length | 4 | 4 | 4 | 4 | 4 |
| s2.length | 4 | 4 | 4 | 4 | 4 |
Anagram Check Techniques: - Check if strings have equal length first - Method 1: Sort both strings and compare - Method 2: Count characters in first string, subtract counts using second - If all counts zero at end, strings are anagrams - Return true if anagram, false otherwise
function areAnagrams(s1: string, s2: string): boolean {
const normalize = (str: string) => str.toLowerCase().replace(/\s+/g, '').split('').sort().join('');
return normalize(s1) === normalize(s2);
}
console.log(areAnagrams('Listen', 'Silent'));
console.log(areAnagrams('Hello', 'Olelh'));
console.log(areAnagrams('Test', 'Taste'));function isAnagram(a: string, b: string): boolean {
return a.split('').sort() === b.split('').sort();
}Pass the test and this pattern moves unknown