Skip to content

Added GroupAnagrams #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 17, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions LeetcodeProblems/GroupAnagrams.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
https://leetcode.com/problems/group-anagrams/description/

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:

All inputs will be in lowercase.
The order of your output does not matter.
*/

var groupAnagrams = function(strs) {
var ret = [];
var hashMap = {};
for(var i = 0; i < strs.length; i++) {
const elem = strs[i];
const elemSorted = sortString(strs[i]);

if(hashMap[elemSorted]) {
hashMap[elemSorted].push(elem);
} else {
hashMap[elemSorted] = [elem];
}
}

for(key in hashMap) {
ret.push(hashMap[key]);
}

return ret;
};

var sortString = function(str) {
if(str.length === 0) {
return str;
}

return str.split("").sort().join("");
}

var main = function() {
console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));
}

module.exports.main = main;