|
| 1 | +// Approach 2 |
| 2 | +// Time Complexity: O(n * L), where n = number of strings in strs, L = maximum length of a string in strs |
| 3 | +// Space Complexity: O(n * L) |
| 4 | + |
| 5 | +function groupAnagrams(strs: string[]): string[][] { |
| 6 | + |
| 7 | + let sorted: { [key: string]: string[] } = {} |
| 8 | + |
| 9 | + for (const str of strs) { |
| 10 | + |
| 11 | + const arr = Array.from({ length: 26 }, () => 0) |
| 12 | + |
| 13 | + for (const ch of str) { |
| 14 | + arr[ch.charCodeAt(0) - "a".charCodeAt(0)] += 1 |
| 15 | + } |
| 16 | + |
| 17 | + // const key = arr.join(""); // This can lead to key collisions. |
| 18 | + const key = arr.join("#"); // ✅ |
| 19 | + |
| 20 | + if (!sorted[key]) { |
| 21 | + sorted[key] = [] |
| 22 | + } |
| 23 | + |
| 24 | + sorted[key].push(str) |
| 25 | + } |
| 26 | + |
| 27 | + return Object.values(sorted); |
| 28 | +}; |
| 29 | + |
| 30 | + |
| 31 | +// Approach 1 |
| 32 | +// Time Complexity: O(n * LlogL), where n = number of strings, L = average length of the strings |
| 33 | +// Space Complexity: O(n * L) |
| 34 | + |
| 35 | +// function groupAnagrams(strs: string[]): string[][] { |
| 36 | +// // input: an array of strings, strs |
| 37 | +// // output: the anagrams |
| 38 | + |
| 39 | +// // eat -> e, a, t -> a, e, t |
| 40 | +// // tea -> t, e, a -> a, e, t |
| 41 | +// // ate -> a, t, e -> a, e, t |
| 42 | + |
| 43 | +// let map = new Map<string, string[]>(); |
| 44 | +// let result: string[][] = []; |
| 45 | + |
| 46 | +// for (const str of strs) { |
| 47 | +// const temp = str.split("").sort().join(""); |
| 48 | + |
| 49 | +// if (map.has(temp)) { |
| 50 | +// map.set(temp, [...map.get(temp)!, str]); |
| 51 | +// } else { |
| 52 | +// map.set(temp, [str]); |
| 53 | +// } |
| 54 | +// } |
| 55 | + |
| 56 | +// for (const el of map.values()) { |
| 57 | +// result.push(el); |
| 58 | +// } |
| 59 | + |
| 60 | +// return result; |
| 61 | +// } |
| 62 | + |
0 commit comments