---
# System prepended metadata

title: 'Valid Anagram <img src="https://img.shields.io/badge/-easy-brightgreen">'
tags: [data_structure_python]

---

---
tags: data_structure_python
---

# Valid Anagram <img src="https://img.shields.io/badge/-easy-brightgreen">

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

<ins>**Example 1:**</ins>

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

<ins>**Example 2:**</ins>

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

**Note:**
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?

# Solution


### Solution 1: First approach

Support unicode characters.

```python=
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # O(nlog(n)) in time complexity.
        # O(1) in space complexity.
        n, m = len(s), len(t)
        
        if n != m:
            return False
        else:
            t = "".join(sorted(t))
            s = "".join(sorted(s))
           
            return t == s
```        

### Solution 2: Second approach

This approach doesn't support unicode characters. The space complexity is O(1) here because for any size of s/t, the array will stil contains 26 elements, thus constant.

```python=
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # O(n) in time complexity.
        # O(1) in space complexity.
        n, m = len(s), len(t)
        
        if n != m:
            return False
        else:
            counter = [0]*26
            
            for letter in s:
                counter[ord(letter) - ord('a')] += 1
        
            for letter in t:
                counter[ord(letter) - ord('a')] -= 1
                if counter[ord(letter) - ord('a')] < 0:
                    return False
                
            return True
```