Skip to content

Commit 9ff11c3

Browse files
authored
Merge pull request ashutosh97#110 from entowan/anagramchecking
Add anagram checking problem
2 parents 170044d + e480cf7 commit 9ff11c3

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

AnagramChecking/anagram_checking.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Python3 program to check if two strings are anagram of each other
2+
3+
def are_anagram(s1, s2):
4+
""" Check if two strings are anagram of each other.
5+
6+
Apply XOR to all characters of both strings. If the final value is 0, then
7+
there is an even occurence of all characters, ie the two strings are
8+
anagram. Otherwise, there are not anagram.
9+
10+
Args:
11+
s1 (str): First string
12+
s2 (str): Second string
13+
14+
Returns:
15+
bool: True if the two strings are anagram of each other, otherwise False
16+
"""
17+
# Two strings with different sizes can not be anagram of each other
18+
if len(s1) != len(s2):
19+
return False
20+
21+
# Apply XOR to all characters of both strings
22+
xor_value = 0
23+
for c1, c2 in zip(s1, s2):
24+
xor_value = xor_value ^ ord(c1)
25+
xor_value = xor_value ^ ord(c2)
26+
27+
return not bool(xor_value)
28+
29+
def main():
30+
""" Driver code """
31+
s1 = 'listen'
32+
s2 = 'silent'
33+
s3 = 'hacktoberfest'
34+
print('{} / {} -> {}'.format(s1, s2, are_anagram(s1, s2)))
35+
print('{} / {} -> {}'.format(s1, s3, are_anagram(s1, s3)))
36+
print('{} / {} -> {}'.format(s2, s3, are_anagram(s2, s3)))
37+
38+
if __name__=='__main__':
39+
main()

AnagramChecking/anagram_checking.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Anagram checking
2+
3+
Write a function that check whether two given strings are anagram of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. An optimized solution should have a O(n) time complexity and O(1) space complexity.

0 commit comments

Comments
 (0)