Skip to content

Commit 8f7c2f8

Browse files
committed
feat: add valid anagram algorithm in Strings folder
1 parent 7530a41 commit 8f7c2f8

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

strings/valid_anagram.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""
2+
Checks whether two strings are valid anagrams of each other.
3+
4+
An anagram is a word formed by rearranging the letters of another word,
5+
using all the original letters exactly once.
6+
7+
For example:
8+
listen → silent
9+
evil → live
10+
11+
This can be done efficiently using Python's collections.Counter
12+
to compare character frequencies in both strings.
13+
14+
Example:
15+
>>> is_anagram("listen", "silent")
16+
True
17+
>>> is_anagram("evil", "vile")
18+
True
19+
>>> is_anagram("hello", "bello")
20+
False
21+
>>> is_anagram("", "")
22+
True
23+
>>> is_anagram("a", "aa")
24+
False
25+
"""
26+
27+
from collections import Counter
28+
29+
30+
def is_anagram(s1: str, s2: str) -> bool:
31+
"""
32+
Returns True if the two input strings are anagrams of each other.
33+
34+
The comparison is case-sensitive and ignores no characters.
35+
36+
>>> is_anagram("listen", "silent")
37+
True
38+
>>> is_anagram("triangle", "integral")
39+
True
40+
>>> is_anagram("apple", "papel")
41+
True
42+
>>> is_anagram("rat", "car")
43+
False
44+
>>> is_anagram("a", "aa")
45+
False
46+
"""
47+
return Counter(s1) == Counter(s2)
48+
49+
50+
if __name__ == "__main__":
51+
import doctest
52+
53+
doctest.testmod()

0 commit comments

Comments
 (0)