smj007

Untitled

Jun 18th, 2022 (edited)
137
1
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.59 KB | None | 1 0
  1. """
  2. Approach: Hash based on sorted string and store the string in the dictionary of list
  3. 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)
  4. """
  5.  
  6. class Solution:
  7.     def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
  8.        
  9.         from collections import defaultdict
  10.         hashset = defaultdict(list)
  11.        
  12.         for s in strs:
  13.             hashset["".join(sorted(s))].append(s)
  14.            
  15.         return hashset.values()
  16.            
  17.            
  18.            
  19.        
Advertisement
Comments
  • kekets
    2 years
    # Python 0.65 KB | 0 0
    1. from collections import defaultdict
    2.  
    3. class Solution:
    4.     def groupAnagrams(self, strs):
    5.         # Initialize a defaultdict to store anagrams grouped by their sorted forms
    6.         hashset = defaultdict(list)
    7.  
    8.         # Loop through each string in the input list
    9.         for s in strs:
    10.             # Sort the characters in the string and join them to form the sorted string
    11.             sorted_str = ''.join(sorted(s))
    12.            
    13.             # Append the original string to the list associated with its sorted form
    14.             hashset[sorted_str].append(s)
    15.  
    16.         # Return a list of grouped anagram lists
    17.         return list(hashset.values())
    18.  
Add Comment
Please, Sign In to add comment