Group Anagrams
Explore how to identify and group anagrams by applying data tracking patterns that monitor character frequencies. This lesson guides you through solving frequency-based problems effectively, helping you master a critical coding interview pattern used to organize and group strings with matching characters.
We'll cover the following...
Statement
Given a list of strings strs, group together all strings that are anagrams of each other.
An anagram is a string formed by rearranging the letters of another string, using all original letters exactly once. For example, “eat”, “tea”, and “ate” are anagrams.
Return a list of groups, where each group contains strings that are anagrams of each other.
Note: The order of the groups and the order of strings within each group does not matter.
Constraints:
Let strs be the list of strings given as input to find the anagrams.
-
strs.length -
strs[i].length strs[i]consists of lowercase English letters.
Examples
Understand the problem
Let’s take a moment to make sure you've correctly understood the problem. The quiz below helps you check if you're solving the correct problem:
Group Anagrams
What is the output if the following list is given as input?
[‘bat’, ‘tab’, ‘tan’, ‘at’]
[[‘at’], [‘bat’], [‘tab’], [‘tan’]]
[[‘at’, ‘bat’]], [[‘tab’, tan’]]
[[‘at’, ‘bat’, ‘tab’, tan’]]
[[‘tab’, ‘bat’]], [‘tan’], [‘at’]]
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
import java.util.*;class GroupAnagrams {public static List<List<String>> groupAnagrams(String[] strs){// Replace this placeholder return statement with your codereturn new ArrayList<>();}}