SDE & MLE Prep

242. Valid Anagram

Problem

Given two strings s and t, decide whether t is an anagram of s: the same letters with the same counts, possibly in a different order.

Example: s = "anagram", t = "nagaram" → true; s = "rat", t = "car" → false

Constraints: lowercase English letters; length ≤ 5·10⁴. Follow-up: what if the input is Unicode?

Anagrams have identical letter counts. Count up for s, down for t; every bucket must end at 0.

Complexity: O(n) time, O(1) space (26 letters).

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        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)