DEV Community

Clark Ngo
Clark Ngo

Posted on

2 1

How to solve Group Anagrams problem

Follow Me, Shout Out, or Give Thanks!

Please 💖 this article. a small thing to keep me motivated =)
Twitter: @djjasonclark
Linkedin: in/clarkngo

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.

Let's work with the following:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Enter fullscreen mode Exit fullscreen mode

Trial 1 - Not efficient:

  1. (plus space) copy input
["eat","tea","tan","ate","nat","bat"]
Enter fullscreen mode Exit fullscreen mode
  1. (plus time) sort copied input
["aet", "aet", "ant", "aet", "ant", "abt"]
Enter fullscreen mode Exit fullscreen mode
  1. (plus space and another space for map/dictionary and plus time) create list and assign same number to same words
[1,1,2,1,2,3]
Enter fullscreen mode Exit fullscreen mode

Well... let's just stop there.

Trial 2 - Hashing:

Hashing? The process of assigning a unique value to an object or attribute using an algorithm, which enables quicker access, is known as hashing.

  1. (plus space and time) iterate over each string and each of its character. in every loop, generate a "hash" by increase value at indices representing character (0 -> 'a', 1 -> 'b')

  2. once you have a hash, add that a key to a map/dictionary (key-> string, val-> list of strings). then insert word/s.

When you reach this.. you already know what to do. =)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post