LeetCode 242. Valid Anagram



Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

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

Example 2:

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

You may assume the string contains only lowercase alphabets.

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


Check if characters in s and t match their occurences.

Python Solution

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        counter = {}
        for char in s:
            if char not in counter:
                counter[char] = 1
                counter[char] += 1
        for char in t:
            if char not in counter:
                return False
                counter[char] -= 1
        for key, value in counter.items():
            if value != 0:
                return False            
        return True
  • Time complexity: O(N).
  • Space complexity: O(1). The space complexity is O(1) because the table’s size stays constant no matter how large n is.

Leave a Reply

Your email address will not be published. Required fields are marked *