You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Your solution for grouping anagrams is correct and demonstrates a good understanding of the problem. Here are some suggestions for improvement:
Consider using a different variable name instead of map, such as anagram_groups or groups, to avoid shadowing the built-in map function.
While using the sorted string as a key is acceptable, for longer strings, you might consider using a tuple of character counts for better performance. For example:
key = tuple(sorted(s)) # This is similar to what you have, but as a tuple which is hashable.
Alternatively, you can use a frequency array converted to a tuple:
count = [0] * 26
for char in s:
count[ord(char) - ord('a')] += 1
key = tuple(count)
This method has a time complexity of O(N * K) which is better when K is large.
You can use defaultdict from the collections module to make the code more concise:
from collections import defaultdict
groups = defaultdict(list)
for s in strs:
key = ''.join(sorted(s))
groups[key].append(s)
return list(groups.values())
This avoids the need to check if the key exists.
Overall, your solution is correct and efficient for most cases. Well done!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.