Skip to content

Commit ad083ec

Browse files
committed
Sync LeetCode submission Runtime - 11 ms (74.27%), Memory - 18 MB (25.35%)
1 parent aed74dc commit ad083ec

File tree

2 files changed

+31
-14
lines changed

2 files changed

+31
-14
lines changed

0242-valid-anagram/README.md

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
1-
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> <em>if</em> <code>t</code> <em>is an anagram of</em> <code>s</code><em>, and</em> <code>false</code> <em>otherwise</em>.</p>
2-
3-
<p>An <strong>Anagram</strong> is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.</p>
1+
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an <span data-keyword="anagram">anagram</span> of <code>s</code>, and <code>false</code> otherwise.</p>
42

53
<p>&nbsp;</p>
64
<p><strong class="example">Example 1:</strong></p>
7-
<pre><strong>Input:</strong> s = "anagram", t = "nagaram"
8-
<strong>Output:</strong> true
9-
</pre><p><strong class="example">Example 2:</strong></p>
10-
<pre><strong>Input:</strong> s = "rat", t = "car"
11-
<strong>Output:</strong> false
12-
</pre>
5+
6+
<div class="example-block">
7+
<p><strong>Input:</strong> <span class="example-io">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p>
8+
9+
<p><strong>Output:</strong> <span class="example-io">true</span></p>
10+
</div>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<div class="example-block">
15+
<p><strong>Input:</strong> <span class="example-io">s = &quot;rat&quot;, t = &quot;car&quot;</span></p>
16+
17+
<p><strong>Output:</strong> <span class="example-io">false</span></p>
18+
</div>
19+
1320
<p>&nbsp;</p>
1421
<p><strong>Constraints:</strong></p>
1522

0242-valid-anagram/solution.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
1-
from collections import Counter
1+
# Approach 2: Frequency Counter
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
26
class Solution:
37
def isAnagram(self, s: str, t: str) -> bool:
4-
s_count = Counter(s)
5-
t_count = Counter(t)
6-
7-
return True if s_count == t_count else False
8+
if len(s) != len(t):
9+
return False
10+
11+
count = [0] * 26
12+
13+
for i in range(len(s)):
14+
count[ord(s[i]) - ord('a')] += 1
15+
count[ord(t[i]) - ord('a')] -= 1
16+
17+
return all(c == 0 for c in count)
818

0 commit comments

Comments
 (0)