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: An anagram means the strings have the same frequency of letters, i.e. abc is anagram of bac or cab, etc.
        • Implementation: Since only lowercase alphabet, increment in 26 value array at each character index (i.e. a = index 0, b = index 1, etc.) for s and decrement for t, if frequency array is zero, return True, otherwise False
          • Complexity: Time O(n), Space O(1) (freq is 26 values, const.)

            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