Problem
Given an array of strings strs
, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]
Example 2:Input: strs = [“”] Output: [[“”]]
Example 3:Input: strs = [“a”] Output: [[“a”]]
Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i]
consists of lowercase English letters.
Solution
First attempt : (Can be optimized further)
var groupAnagrams = function(strs) {
let output = [];
let done = new Set();
if(strs.length == 0){
return [[""]];
}
else if(strs.length == 1){
return [strs];
}
else{
for(let i = 0; i<strs.length; i++){
let group = [strs[i]];
//console.log(done);
if(!done.has(strs[i])){
for(let j = i+1; j<strs.length;j++){
if(isAnagram(strs[i],strs[j])){
group.push(strs[j])
done.add(strs[j])
// strs.splice(j, 1);
}
}
done.add(strs[i]);
//strs.splice(i, 1);
output.push(group);
}
}
}
return output;
};
function isAnagram(stra,strb){
let straa = stra.split("");
let strbb = strb.split("");
if(straa.length == strbb.length){
let obj = {};
for(let i = 0; i < straa.length;i++){
if(obj[straa[i]]){
obj[straa[i]]++;
}
else{
obj[straa[i]] = 1;
}
}
for(let i = 0; i < strbb.length;i++){
if(obj[strbb[i]]){
obj[strbb[i]]--;
}
else{
return false;
}
}
}
else{
return false;
}
return true;
}
Optimized solution:
var groupAnagrams = function(strs) {
let map = new Map();
for(let str of strs) {
let sorted = [...str].sort().join('');
if(map.has(sorted)) {
map.get(sorted).push(str);
} else {
map.set(sorted, [str]);
}
}
return Array.from(map.values());
};
A freelance web developer with a decade of experience in creating high-quality, scalable web solutions. His expertise spans PHP, WordPress, Node.js, MySQL, MongoDB, and e-commerce development, ensuring a versatile approach to each project. Aadi’s commitment to client satisfaction is evident in his track record of over 200 successful projects, marked by innovation, efficiency, and a customer-centric philosophy.
As a professional who values collaboration and open communication, Aadi has built a reputation for delivering projects that exceed expectations while adhering to time and budget constraints. His proactive and problem-solving mindset makes him an ideal partner for anyone looking to navigate the digital landscape with a reliable and skilled developer.