CSInterviewing
Problems
Register
Login
Problems
Register
Login
menu
Valid Anagram
string
hashtable
sorting
# Valid Anagram ## Difficulty Easy ## Tags `string`, `hash table`, `sorting` ## Problem Statement Given two strings `s` and `t`, return `True` if `t` is an anagram of `s`, and `False` otherwise. An anagram is a word formed by rearranging the letters of another word, using all the original letters exactly once. ## Constraints - 1 ≤ s.length, t.length ≤ 5 × 10⁴ - `s` and `t` consist of lowercase English letters. ## Signatures ### Python ```python def is_anagram(s: str, t: str) -> bool: pass ``` ### Java ```java public class Solution { public boolean is_anagram(String s, String t) { return null; } } ``` ### Csharp ```csharp public class Solution { public bool is_anagram(string s, string t) { throw new NotImplementedException(); } } ``` ### Cpp ```cpp class Solution { public: bool is_anagram(string s, string t) { } }; ``` ### C ```c bool is_anagram(char* s, char* t) { } ``` ### Ruby ```ruby def is_anagram(s, t) end ``` ### Perl ```perl sub is_anagram { my ($self, @args) = @_; } ``` ### Scala ```scala object Solution { def is_anagram(s: String, t: String): Boolean = { } } ``` ### Haskell ```haskell is_anagram :: ... -> ... is_anagram args = undefined ``` ### Clojure ```clojure (defn is_anagram [s t] ) ``` ### Scheme ```scheme (define (is_anagram s t) ) ``` ## Examples ### Example 1 **Input:** ``` s = "anagram" t = "nagaram" ``` **Output:** ``` True ``` **Explanation:** Both strings contain: a(3), n(1), g(1), r(1), m(1). ### Example 2 **Input:** ``` s = "rat" t = "car" ``` **Output:** ``` False ``` **Explanation:** Different characters - 't' vs 'c'. ### Example 3 **Input:** ``` s = "listen" t = "silent" ``` **Output:** ``` True ``` ## Hints 1. If the strings have different lengths, they cannot be anagrams. 2. Use a frequency array of size 26 (for 'a' to 'z'). 3. Increment counts for characters in `s`, decrement for `t`. 4. If all counts are zero at the end, they are anagrams. 5. Alternative: Sort both strings and compare.
Login required
Please log in to view the solution editor and submit code.
Login
Register