LeetCode 0049. Group Anagrams Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0049. Group Anagrams

Description

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.

Solutions

Solution 1: Hash Table

  1. Traverse the string array, sort each string in character dictionary order to get a new string.
  2. Use the new string as key and [str] as value, and store them in the hash table (HashMap<String, List<String>>).
  3. When encountering the same key during subsequent traversal, add it to the corresponding value.

Take strs = ["eat", "tea", "tan", "ate", "nat", "bat"] as an example. At the end of the traversal, the state of the hash table is:

key value
"aet" ["eat", "tea", "ate"]
"ant" ["tan", "nat"]
"abt" ["bat"]

Finally, return the value list of the hash table.

The time complexity is O(n× k× log k), where n and k are the lengths of the string array and the maximum length of the string, respectively.

PythonJavaC++GoTypeScriptRustC#
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: d = defaultdict(list) for s in strs: k = ''.join(sorted(s)) d[k].append(s) return list(d.values())(code-box)

Solution 2: Counting

We can also change the sorting part in Solution 1 to counting, that is, use the characters in each string s and their occurrence times as key, and use the string s as value to store in the hash table.

The time complexity is O(n× (k + C)), where n and k are the lengths of the string array and the maximum length of the string, respectively, and C is the size of the character set. In this problem, C = 26.

PythonJavaC++GoTypeScript
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: d = defaultdict(list) for s in strs: cnt = [0] * 26 for c in s: cnt[ord(c) - ord('a')] += 1 d[tuple(cnt)].append(s) return list(d.values())(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !