Isaac Tonyloi
Posted on February 19, 2023
LeetCode is a popular platform that offers various coding challenges and problems. One of the most interesting categories of
The problem we will be solving is "Group Anagrams," which can be found on LeetCode under the ID "49." This problem requires us to group an array of strings into groups of anagrams. An anagram is a word or phrase formed by rearranging the letters of another word or phrase. For example, "listen" and "silent" are anagrams.
The problem statement provides us with an array of strings, and our task is to group them into anagrams. We can approach this problem by using a hash table. We will iterate through each string in the array and sort the characters in the string. We will then use the sorted string as a key to a dictionary and add the original string to the value of that key. Finally, we will return the values of the dictionary as a list.
def groupAnagrams(strs):
dict = {}
for s in strs:
key = ''.join(sorted(s))
if key in dict:
dict[key].append(s)
else:
dict[key] = [s]
return list(dict.values())
Posted on February 19, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.