Skip to content

3 problems completed#2262

Open
BharathVuppala96 wants to merge 2 commits intosuper30admin:masterfrom
BharathVuppala96:master
Open

3 problems completed#2262
BharathVuppala96 wants to merge 2 commits intosuper30admin:masterfrom
BharathVuppala96:master

Conversation

@BharathVuppala96
Copy link
Copy Markdown

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants