DEV Community

smolthing
smolthing

Posted on

leetcode 49. Group Anagrams (python)

https://leetcode.com/problems/group-anagrams

Solution 1

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        sortedKeyDict = defaultdict(list)

        for i in strs:
            sortedKey = sorted(i)
            sortedKeyInString = ''.join(sortedKey)
            sortedKeyDict[sortedKeyInString].append(i)

        return list(sortedKeyDict.values())
Enter fullscreen mode Exit fullscreen mode
  1. Use sorted word as dictionary key

Time Complexity: O(nklog(k))
Space Complexity: O(nk)

Solution 2

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        sortedKeyDict = defaultdict(list)

        for i in strs:
            characterFrequency = [0]*26
            for j in i:
                index = ord(j) - ord('a')
                characterFrequency[index] += 1
            sortedKeyDict[tuple(characterFrequency)].append(i)

        return list(sortedKeyDict.values())
Enter fullscreen mode Exit fullscreen mode
  1. Use character frequency count as dictionary key
  2. Convert list to tuple to make it hashable as dictionary key

Time Complexity: O(nk)
Space Complexity: O(nk)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs