Logo for ammarahmed.ca
Easy
Dec 22, 2025
#hashmap
#frequency

242. Valid Anagram

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

Example 1:

Input: s = "anagram", t = "nagaram"

Output: true

Example 2:

Input: s = "rat", t = "car"

Output: false

Constraints:

  • 1 <= s.length, t.length <= 5 * 104
    • s and t consist of lowercase English letters.

      Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

      Notes

      Intuition

      Two strings are anagrams if they contain the same characters with the same frequencies. A fixed-size frequency array can track character counts efficiently.

      Implementation

      Create a 26-element array for lowercase letters. Iterate through string s, incrementing the count at each character's index (ord(char) - ord('a')). Then iterate through t, decrementing the counts. If the strings are anagrams, all counts will be zero at the end.

      Edge-cases

      Strings of different lengths cannot be anagrams. This is implicitly checked—the frequency array won't be all zeros if lengths differ.

      • Time: O(n) — two passes through the strings
        • Space: O(1) — frequency array is fixed at 26 elements

          Complexity

          Solution

          1class Solution: 2 def isAnagram(self, s: str, t: str) -> bool: 3 freq = [0] * 26 4 5 for char in s: 6 freq[ord(char) - ord('a')] += 1 7 8 for char in t: 9 freq[ord(char) - ord('a')] -= 1 10 11 return all(f == 0 for f in freq) 12 13 14 15 16if __name__ == "__main__": 17 # Include one-off tests here or debugging logic that can be run by running this file 18 # e.g. print(solution.two_sum([1, 2, 3, 4], 3)) 19 solution = Solution() 20