-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path242_Valid_Anagram.py
94 lines (72 loc) · 2.16 KB
/
242_Valid_Anagram.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'''
242. Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
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.
'''
# Brute Force
# Time Complexity: O(nlogn)
# Space Complexity: O(n)
'''
In this approach, we will sort both the strings and iterate through sorted strings. If elements are not equal, then return False, else return True.
'''
class Solution:
def isAnagram(self, s, t):
if len(s)!=len(t):
return False
s1=sorted(s)
t1=sorted(t)
for i,j in zip(s1,t1):
if i!=j:
return False
return True
# Solution 2
# Time Complexity: O(nlogn)
# Space Complexity: O(n)
'''
In this approach, we will sort both the strings and compare them. If they are equal, then return True, else return False.
'''
class Solution:
def isAnagram(self, s, t):
if len(s)!=len(t):
return False
return sorted(s)==sorted(t)
# Solution 3
# Time Complexity: O(n)
# Space Complexity: O(1) (or O(n) for large character sets)
'''
This approach uses a dictionary to store the count of characters in both strings.
If the count of characters in both strings is equal, then return True, else return False.
'''
class Solution:
def isAnagram(self, s, t):
if len(s)!=len(t):
return False
count_s = {}
count_t = {}
for i in range(len(s)):
count_s[s[i]] = count_s.get(s[i], 0) + 1
count_t[t[i]] = count_t.get(t[i], 0) + 1
return count_s==count_t
# Solution 4
# Time Complexity: O(n)
# Space Complexity: O(1) (or O(n) for large character sets)
'''
This approach uses inbuilt Counter function to store the count of characters in both strings.
If the count of characters in both strings is equal, then return True, else return False.
'''
from collections import Counter
class Solution:
def isAnagram(self, s, t):
return Counter(s)==Counter(t)
obj = Solution()
s="racecar"
t="carrace"
print(obj.isAnagram(s,t))