Skip to content

Commit

Permalink
refactor: 49. Group Anagrams
Browse files Browse the repository at this point in the history
  • Loading branch information
gwbaik9717 committed Jan 4, 2025
1 parent 040d1c5 commit 1e90ed0
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions group-anagrams/gwbaik9717.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// n: length of strs, m: length of strs[i]
// Time complexity: O(nmlogm)
// Time complexity: O(nm)
// Space complexity: O(n)

/**
Expand All @@ -10,21 +10,29 @@ var groupAnagrams = function (strs) {
const answer = [];
const anagramDict = new Map();

const sortedStrs = strs.map((str) => {
const splitted = str.split("");
splitted.sort();
return splitted.join("");
});
const getKey = (str) => {
const counter = Array.from(
{ length: "z".charCodeAt() - "a".charCodeAt() + 1 },
() => 0
);

for (let i = 0; i < sortedStrs.length; i++) {
const sortedStr = sortedStrs[i];
const originalStr = strs[i];
for (const chr of str) {
const index = chr.charCodeAt() - "a".charCodeAt();
counter[index]++;
}

return counter.join("#");
};

for (let i = 0; i < strs.length; i++) {
const str = strs[i];
const key = getKey(str);

if (!anagramDict.has(sortedStr)) {
anagramDict.set(sortedStr, []);
if (!anagramDict.has(key)) {
anagramDict.set(key, []);
}

anagramDict.get(sortedStr).push(originalStr);
anagramDict.get(key).push(str);
}

for (const [_, value] of anagramDict) {
Expand Down

0 comments on commit 1e90ed0

Please sign in to comment.