|
| 1 | +// Approach 2 |
| 2 | +// 🗓️ 2025-04-06 |
| 3 | +// ⏳ Time Complexity: O(n) |
| 4 | +// 💾 Space Complexity: O(n) |
| 5 | + |
| 6 | +function isAnagram(s: string, t: string): boolean { |
| 7 | + const map = new Map<string, number>(); |
| 8 | + |
| 9 | + for (const char of s) { |
| 10 | + map.set(char, (map.get(char) || 0) + 1); |
| 11 | + } |
| 12 | + |
| 13 | + for (const char of t) { |
| 14 | + if (!map.has(char)) return false; |
| 15 | + map.set(char, map.get(char)! - 1); |
| 16 | + if (map.get(char) === 0) { |
| 17 | + map.delete(char); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + return map.size === 0; |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +// Approach 1 |
| 26 | +// ⏳ Time Complexity: O(n) |
| 27 | +// 💾 Space Complexity: O(n) |
| 28 | + |
| 29 | +// function isAnagram(s: string, t: string): boolean { |
| 30 | +// const s_map = new Map<string, number>(); |
| 31 | +// const t_map = new Map<string, number>(); |
| 32 | + |
| 33 | +// for (const char of s) { |
| 34 | +// s_map.set(char, (s_map.get(char) || 0) + 1); |
| 35 | +// } |
| 36 | + |
| 37 | +// for (const char of t) { |
| 38 | +// t_map.set(char, (t_map.get(char) || 0) + 1); |
| 39 | +// } |
| 40 | + |
| 41 | +// // Compare the keys and values of both maps |
| 42 | +// if ([...s_map.keys()].length !== [...t_map.keys()].length) { |
| 43 | +// return false; |
| 44 | +// } else { |
| 45 | +// for (const char of [...s_map.keys()]) { |
| 46 | +// if (s_map.get(char) !== t_map.get(char)) { |
| 47 | +// // Lookup operations in Map are O(1) |
| 48 | +// return false; |
| 49 | +// } |
| 50 | +// } |
| 51 | +// } |
| 52 | + |
| 53 | +// return true; |
| 54 | +// } |
| 55 | + |
0 commit comments