Similar Problems
Similar Problems not available
Groups Of Strings - Leetcode Solution
Companies:
LeetCode: Groups Of Strings Leetcode Solution
Difficulty: Hard
Topics: union-find string bit-manipulation
Problem Statement:
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
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.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
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.
Approach:
The problem can be solved using the hashmap data structure in order to group the anagrams together.
-
Define a hash map. The key of the map will be sorted string and value will be list of anagram words.
-
Loop through the strings in the given input list “strs”
-
Sort each string and group strings with the same sorted string in a list
-
Return the list of lists.
Algorithm:
-
Create a data structure a hashmap, where the key will be the sorted form of each word in array and value will be a list of strings.
-
Loop through the strings in the given input list "strs".
-
Sort each string and group its anagrams together by appending it to same list in hashmap.
-
Loop through the keys of hashmap and store the string values in a separate list.
-
Return this list.
Pseudo-code:
def groupAnagrams(strs: List[str]) -> List[List[str]]: anagramGroups = {}
# Loop through each string in strs list
for s in strs:
# Sort the string and store a key in the map
sortedString = ''.join(sorted(s))
# Append the original string to the list
if sortedString in anagramGroups:
anagramGroups[sortedString].append(s)
else:
anagramGroups[sortedString] = [s]
# Return the list of anagram groups
return list(anagramGroups.values())
Code:
class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ anagramGroups = {}
# Loop through each string in strs list
for s in strs:
# Sort the string and store a key in the map
sortedString = ''.join(sorted(s))
# Append the original string to the list
if sortedString in anagramGroups:
anagramGroups[sortedString].append(s)
else:
anagramGroups[sortedString] = [s]
# Return the list of anagram groups
return list(anagramGroups.values())
Groups Of Strings Solution Code
1