Valid Anagram (LeetCode 242): Interview Notes

Given two strings s and t, return true if t is an anagram of s.

Approach

Count character frequencies. With lowercase English letters, a length-26 array is enough: increment for s, decrement for t, then check all zeros. Mention the hashmap variant for Unicode.

def isAnagram(s, t):
    if len(s) != len(t):
        return False
    cnt = [0] * 26
    for a, b in zip(s, t):
        cnt[ord(a) - 97] += 1
        cnt[ord(b) - 97] -= 1
    return all(c == 0 for c in cnt)

Complexity

Time O(n), space O(1) for fixed alphabet.

Rehearse aloud with AI interview copilot before the real call.

Disclosure: I work on Linkjob AI.