DEV Community

Isaac Tonyloi
Isaac Tonyloi

Posted on

1

Anagram solution

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())

Enter fullscreen mode Exit fullscreen mode

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay