Read-only web browser

Solutions

Browse the interview solutions folder with syntax highlighting.

valid-anagram.py

array-hashing/valid-anagram.py · Python · 826 B · 2026-02-17 21:01

Back to folder
# Use hash map to count character occurrences.
# hash-map,strings

# Sorting, O(nlogn) time, O(1) space
def isAnagram(s: str, t: str) -> bool:
    if len(s) != len(t):
        return False
    return sorted(s) == sorted(t)

# Hash map, O(n) time, O(1) space
def isAnagram(s: str, t: str) -> bool:
    if len(s) != len(t):
        return False

    countS, countT = {}, {}
    for i in range(len(s)):
        countS[s[i]] = 1 + countS.get(s[i], 0)
        countT[t[i]] = 1 + countT.get(t[i], 0)
    return countS == countT

# Hash table using array, O(n) time, O(1) space
def isAnagram(s: str, t: str) -> bool:
    if len(s) != len(t):
        return False

    count = [0] * 26
    for i in range(len(s)):
        count[ord(s[i]) - ord('a')] += 1
        count[ord(t[i]) - ord('a')] -= 1

    return all(x == 0 for x in count)