Taro Logo

Group Anagrams

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+67
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
4.4K views
Topics:
ArraysStrings

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]

Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Explanation:

  • There is no string in strs that can be rearranged to form "bat".
  • The strings "nat" and "tan" are anagrams as they can be rearranged to form each other.
  • The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.

Example 2:

Input: strs = [""]

Output: [[""]]

Example 3:

Input: strs = ["a"]

Output: [["a"]]

Constraints:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the character set of the strings? Should I assume only lowercase English letters, or can there be uppercase letters, spaces, or Unicode characters?
  2. What should we return if the input array is empty (`strs = []`)?
  3. Can the input array contain duplicate strings, and if so, should they be grouped together in the same list?
  4. Is there any specific ordering required for the groups in the output array, or for the strings within each group?
  5. What is the maximum length of the strings and the maximum number of strings in the array (`strs`)?

Brute Force Solution

Approach

Imagine you have a big pile of words written on slips of paper and you need to sort them so that words made of the exact same letters are grouped together. The brute force approach relies on exhaustively comparing every single word against every other word to check if they are anagrams.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first word in your pile and create a new group for it.
  2. Take the next word in the pile and test it against all the words already in your existing groups to see if it is an anagram of them.
  3. To test if two words are anagrams, check if they can be formed using the exact same set of letters by looking closely at their spelling.
  4. If the word matches the letters of any word in an existing group, place it into that group.
  5. If the word does not match any existing group, create a brand new group just for this word.
  6. Repeat this checking and sorting process for every remaining word in the pile one by one.
  7. Once every single word has been checked and placed into a group, gather all the groups together as your final answer.

Code Implementation

def group_anagrams(input_words):
    grouped_anagrams = []

    # We group words by checking if they share identical sorted letters to identify anagrams
    for current_word in input_words:
        found_matching_group = False

        for group in grouped_anagrams:
            if sorted(current_word) == sorted(group[0]):
                group.append(current_word)
                found_matching_group = True
                break

        # If no existing group matches the current word, we must initialize a new group
        if not found_matching_group:
            new_group = [current_word]
            grouped_anagrams.append(new_group)

    return grouped_anagrams

Big(O) Analysis

Time Complexity
O(n²) – For each of the n words in our input pile, the strategy requires us to compare it against our existing groups of words. In the worst case where every word belongs to a different group, checking a word against all previously established groups takes proportional time to the number of groups formed so far. This means we compare the first word against 0 groups, the second against 1, the third against 2, and so on up to n-1 groups. Summing these comparisons yields approximately n * n/2 operations, which simplifies to a quadratic O(n²) time complexity.
Space Complexity
O(N * K) – The auxiliary space is driven by a hash map used to store the groups of anagrams, where N is the total number of words in the input and K is the maximum length of a word. In the worst-case scenario where no words are anagrams, the hash map and its lists store all N words and their string keys, requiring extra memory proportional to the total characters across all words.

Optimal Solution

Approach

To efficiently group words that are anagrams of each other, we can use a sorting shortcut to give every anagram a matching identity label. By organizing items into labeled bins based on this uniform signature, we can instantly gather all matching words together in a single pass.

Here's how the algorithm would work step-by-step:

  1. Take each word from your collection and rearrange its letters into alphabetical order, so that words made of the exact same letters will end up looking identical.
  2. Use this sorted letter arrangement as a shared name tag or label for that word.
  3. Picture a set of storage boxes where each box is labeled with one of these sorted letter combinations.
  4. Go through your original list of words one by one, looking at each word's specific label.
  5. Place each word directly into the storage box that matches its unique label, automatically keeping all true anagrams together.
  6. Once every word has been placed into its correct box, gather the contents of all the boxes to form your final groups.

Code Implementation

def group_anagrams(word_collection):
    storage_bins = {}

    # Sorting characters creates a uniform identity label for any anagram pair.
    for current_word in word_collection:
        identity_label ="".join(sorted(current_word))

        # Using a hash map groups words efficiently without nested iterations.
        if identity_label not in storage_bins:
            storage_bins[identity_label] = []

        storage_bins[identity_label].append(current_word)

    # Extracting bin values gathers all processed anagram groups together.
    return list(storage_bins.values())

Big(O) Analysis

Time Complexity
O(n * k log k) – To analyze the time complexity, let n be the number of words in the input collection and k be the maximum length of a word. For each of the n words, we must rearrange its letters into alphabetical order, which takes O(k log k) time per word using a sorting algorithm. We then perform hash map insertions and lookups to group the words by their sorted signature, which takes O(1) time on average per word. Multiplying the word processing cost across all items yields approximately n * (k log k) total operations. Simplifying this expression by dropping constant factors gives the final Big O time complexity of O(n * k log k).
Space Complexity
O(N * K) – To group the anagrams, we use a hash map where the keys are sorted letter strings and the values are lists of original words, along with temporary character arrays created during the sorting of each word. If N is the number of strings and K is the maximum length of a string, storing all N strings in the hash map requires auxiliary space proportional to the total characters. Therefore, the extra memory grows linearly with the combined size of all inputs, resulting in O(N * K) auxiliary space complexity.

Edge Cases

Empty input array of strings
How to Handle:
Return an empty list immediately without entering the processing loop.
Array containing a single string
How to Handle:
Return a nested list containing just that single string as its own group.
Strings containing empty string elements
How to Handle:
An empty string acts as its own valid anagram group and hashes correctly to an empty count key.
All strings in the array are identical
How to Handle:
They will all map to the same signature key and accumulate into a single group list.
No anagrams exist among the strings
How to Handle:
Every string will form a distinct signature key and be returned as a separate single-element list.
Strings with mixed uppercase and lowercase letters
How to Handle:
Since standard anagram problems are case-sensitive, treat different cases as distinct characters unless explicitly normalized.
Extremely long strings or massive input arrays
How to Handle:
Use a character frequency count array instead of sorting each string to guarantee linear time scaling per string.
Unicode characters or non-ASCII alphabets within strings
How to Handle:
Use a hash map with character frequency counts instead of a fixed size integer array to safely support extended character sets.
0/75 completed