Group Anagrams (Leetcode #49)
I am a beginner coder who wants to keep track of my coding progress. I will post my LeetCode solutions here. Please feel free to give me advice or suggestions on my code.
Also, in the future, I will be posing my data science-related project here as well
Question:
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:
[
0 <= strs[](https://leetcode.com/problems/group-anagrams/)i].length<= 100strs[i]consists of lowercase English letters.
Answer:
Create a hashmap to keep track of each word where the key is the sorted word and the values will be the original word
Return the values of the hashmap in a list form
word = {}
for w in strs:
sorted_string = "".join(sorted(w))
if sorted_string not in word:
word[sorted_string] = []
word[sorted_string].append(w)
return list(word.values())
Time complexity
Let's break this down into each part.
Loop each item in strs will cost you O(N)
Sorting string with average length K will cost you O(klogk)
Hence the overall time complexity will be O(n * k log k)
Space Complexity
When we sort the text we need a temporary space of O(k)
We need to store each sorted string in the hashmap
The overall space complexity will be O(n * k)