Leetcode Solution To problem 49
Chinaza Adimoha
Senior Frontend Developer | Typescript | ReactJS Developer | Next JS && SSR | Fintech | Banking(Core Banking) | HealthTech (EHR) | Real Estate Tech | Creating Responsive High Performance Software Products |
Hello Guys, It's your favorite Agba Coder, Lol.
Today I will walk you through my thought process, in solving the Grouped Anagram problem on Leetcode. This very problem, expanded my mind further, as I had already solved something similar in the previous days, which was the Anagram problem.
So basically, an Anagram is a word, phrase, or even a name formed by transposing the letter of another word. Simply put, it is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Problem Definition:
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
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"]]
Solution:
领英推è
var groupAnagrams = function(strs) {
//first instantiate a variable called group
const group = {};
//I want to loop through the object
for(let i of strs){
//i want to sort the values of strs and make value at I to be a key
let sortedKey = i.split('').sort().join('');
console.log(sortedKey)
//what the logged value looks like:
aet
aet
ant
aet
ant
abt
//I want check if the sortedKeys exist in the object
if(!group[sortedKey]){
group[sortedKey] = [i]
//if it is not found, equate it to the original keys like "eat"
} else {
group[sortedKey].push(i)
}
}
console.log("group", group)
//what the logged value looks like:
group: { aet: [ 'eat', 'tea', 'ate' ], ant: [ 'tan', 'nat' ], abt: [ 'bat' ] }
//now i want to return the values of the object group
return (Object.values(group))
};
The time complexity of my solution was o(n)
If you found this post insightful, please engage, repost, and share your thoughts.
Best Regards Guys
Full Stack Developer | React.js | Node.js | Express.js | MongoDB | HTML5 | CSS | JavaScript | Tailwind CSS | Skilled in Frontend and Backend Development
1 å¹´Impressive! Chinaza Adimoha
Software Engineer | Angular | React | NextJs | Remix | Node.js | NestJs | Ionic | TypeScript | Large Language Models (LLM)
1 å¹´Love this, simplified Solution, weldone my tech gee.