> [!META]- Inline Metadata > [tags:: #career #leetcode/arrays ] > [project group:: Neetcode 150] > [difficulty:: easy] > [status:: in progress] > [link::] > [up:: [[Leetcode MOC]]] ## Problem Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **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? ## Solution ### Mine #### Python ```python class Solution: def isAnagram(self, s: str, t: str) -> bool: return sorted(s) == sorted(t) ``` #### Rust ### LC's (not official) ```python class Solution: def isAnagram(self, s: str, t: str) -> bool: flag = True if len(s) != len(t): flag = False else: letters = "abcdefghijklmnopqrstuvwxyz" for letter in letters: if s.count(letter) != t.count(letter): flag = False break return flag ``` This is roughly $O(n)$ because of the `string.count()` calls. ## Things I Learned ## Scratchpad If an anagram is a collection of the same characters, simply checking for equality between the strings being sorted would work. It might not be the most performant, but it's a good first stab. ### From Neetcode Video Easy method would be to use a dictionary that holds each character and their count, and compare them. Time and memory are both $O(s + t)$. Check for length equality first. ```python class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False count_s, count_t = {}, {} for i in range(len(s)): count_s[s[i]] = 1 + count_s.get(s[i], 0) # can apply to t as well since they're the same length count_t[t[i]] = 1 + count_t.get(t[i], 0) for c in count_s.keys(): if count_s[c] != count_t.get(c): return False return True ``` ^x8bdwa Can concisely do this Python only with Counter: ```python class Solution: def isAnagram(self, s: str, t: str) -> bool: return Counter(s) == Counter(t) ``` ^icdr3v What about $O(1)$ memory? - Use `sorted`, but increases time complexity and may increase space (interviewers sometimes assume sorting doesn't take extra space) -