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.
Leetcode Difficulty: Medium
Asked in: Facebook Amazon ,Apple Netflix Google
Code:
def groupanagrams(self, strs): """ strs: List[str] return: List[List[str]] """ if len(strs)==0: return [[""]] elif len(strs)==1: return [[strs[0]]] ans = collections.defaultdict(list) for s in strs: ans[tuple(sorted(s))].append(s) return ans.values()
Thought Process / Explanation:
The keyword "grouping" hints me to use a dictionary where key will be a common representation of strings and value be their original form. Also, we know that sorted anagrams represent the exact same string.
Thank You!
No comments:
Post a Comment
Please share your valuable feedback. It will help me and community grow.