Read-only web browser

Solutions

Browse the interview solutions folder with syntax highlighting.

group-anagrams.py

array-hashing/group-anagrams.py · Python · 652 B · 2026-02-17 21:00

Back to folder
# Sorting or hash table based on set of letters
# hash-map
# Sorting, O(m*nlogn) time, O(m) space
def groupAnagrams(strs: list[str]) -> list[list[str]]:
    anagrams = {}
    for s in strs:
        key = ''.join(sorted(s))
        anagrams[key] = anagrams.get(key, []) + [s]
    return list(anagrams.values())

# Hash table using array, O(n*m) time, O(m) space
def groupAnagrams(strs: list[str]) -> list[list[str]]:
    anagrams = {}
    for s in strs:
        counter = [0] * 26
        for c in s:
            counter[ord(c) - ord('a')] += 1
        anagrams[tuple(counter)] = anagrams.get(tuple(counter), []) + [s]
    return list(anagrams.values())