kekets

Anagram Grouping using Hashing and Sorting

Aug 16th, 2023
984
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.64 KB | None | 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())
Advertisement
Add Comment
Please, Sign In to add comment