From 1578bc52d6feb80b8cb33b2664913b862bd10a2f Mon Sep 17 00:00:00 2001 From: Sangeeth Sudheer Date: Thu, 21 Apr 2022 13:32:57 +0530 Subject: [PATCH] add valid-anagram --- 0242_valid-anagram/README.md | 22 ++++++++++++++++++++++ 0242_valid-anagram/python3/nlogn.py | 13 +++++++++++++ 0242_valid-anagram/python3/oneliner.py | 8 ++++++++ 0242_valid-anagram/python3/solution.py | 21 +++++++++++++++++++++ 4 files changed, 64 insertions(+) create mode 100644 0242_valid-anagram/README.md create mode 100644 0242_valid-anagram/python3/nlogn.py create mode 100644 0242_valid-anagram/python3/oneliner.py create mode 100644 0242_valid-anagram/python3/solution.py diff --git a/0242_valid-anagram/README.md b/0242_valid-anagram/README.md new file mode 100644 index 0000000..5a4fc81 --- /dev/null +++ b/0242_valid-anagram/README.md @@ -0,0 +1,22 @@ +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? \ No newline at end of file diff --git a/0242_valid-anagram/python3/nlogn.py b/0242_valid-anagram/python3/nlogn.py new file mode 100644 index 0000000..4c7d66b --- /dev/null +++ b/0242_valid-anagram/python3/nlogn.py @@ -0,0 +1,13 @@ +# Time: O(NlogN) +# Space: O(1) + +from collections import Counter + +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + slen, tlen = len(s), len(t) + + if slen != tlen: + return False + + return sorted(s) == sorted(t) diff --git a/0242_valid-anagram/python3/oneliner.py b/0242_valid-anagram/python3/oneliner.py new file mode 100644 index 0000000..e770ea2 --- /dev/null +++ b/0242_valid-anagram/python3/oneliner.py @@ -0,0 +1,8 @@ +# Time: O(N) +# Space: O(N) + +from collections import Counter + +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return Counter(s) == Counter(t) diff --git a/0242_valid-anagram/python3/solution.py b/0242_valid-anagram/python3/solution.py new file mode 100644 index 0000000..3f50558 --- /dev/null +++ b/0242_valid-anagram/python3/solution.py @@ -0,0 +1,21 @@ +# Time: O(N) where N is num of chars in string +# Space: O(N) where N is num of chars in string + +from collections import Counter + +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + slen, tlen = len(s), len(t) + + if slen != tlen: + return False + + scounts, tcounts = {}, {} + + for i in range(slen): + sc, tc = s[i], t[i] + + scounts[sc] = scounts.get(sc, 0) + 1 + tcounts[tc] = tcounts.get(tc, 0) + 1 + + return scounts == tcounts