Tap here to switch tabs
Problem
Submissions
Solution

Solution: Group Anagrams

Statement

Naive approach

The naive approach is to sort all strings first, and then compare them to check whether they are identical. The idea is that if two strings are anagrams, sorting them both will always make them equal to each other. For example, consider the strings “car” and “arc”. When sorted, both these strings become “acr”.

We’ll initialize a hash map to store the anagrams where the key represents the sorted string and the value represents the array of anagrams corresponding to that key. We’ll run a loop on the given list of strings. On each iteration, we will sort the current string. We’ll then check if the sorted string is present as a key in the hash map. If it is, we’ll append the original, unsorted string to the array corresponding to that key. Otherwise, we’ll add the new key-value pair to the hash map. At the end of the traversal, the hash map will contain all the groups of anagrams.

We’ll need O(n)O(n) time to traverse the list of strings of length nn ...

Tap here to switch tabs
Problem
Submissions
Solution

Solution: Group Anagrams

Statement

Naive approach

The naive approach is to sort all strings first, and then compare them to check whether they are identical. The idea is that if two strings are anagrams, sorting them both will always make them equal to each other. For example, consider the strings “car” and “arc”. When sorted, both these strings become “acr”.

We’ll initialize a hash map to store the anagrams where the key represents the sorted string and the value represents the array of anagrams corresponding to that key. We’ll run a loop on the given list of strings. On each iteration, we will sort the current string. We’ll then check if the sorted string is present as a key in the hash map. If it is, we’ll append the original, unsorted string to the array corresponding to that key. Otherwise, we’ll add the new key-value pair to the hash map. At the end of the traversal, the hash map will contain all the groups of anagrams.

We’ll need O(n)O(n) time to traverse the list of strings of length nn ...