Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Approach: Hash based on sorted string and store the string in the dictionary of list
- Time Complexity: O(NKlogK) where N is the length of the outer array and K is the maximum lengh of string in strs. The outer loop has complexity has O(N)
- """
- class Solution:
- def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
- from collections import defaultdict
- hashset = defaultdict(list)
- for s in strs:
- hashset["".join(sorted(s))].append(s)
- return hashset.values()
Advertisement
Comments
-
- from collections import defaultdict
- class Solution:
- def groupAnagrams(self, strs):
- # Initialize a defaultdict to store anagrams grouped by their sorted forms
- hashset = defaultdict(list)
- # Loop through each string in the input list
- for s in strs:
- # Sort the characters in the string and join them to form the sorted string
- sorted_str = ''.join(sorted(s))
- # Append the original string to the list associated with its sorted form
- hashset[sorted_str].append(s)
- # Return a list of grouped anagram lists
- return list(hashset.values())
Add Comment
Please, Sign In to add comment