Skip to content

Commit 1061568

Browse files
authored
Merge pull request prabhupant#68 from yashyasviagarwal/feat-add-new_string_question
added a new string question
2 parents a4b087d + fcb4e93 commit 1061568

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Question:
3+
Check whether two strings are anagram of each other:
4+
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other.
5+
Source:A very Common Interview Question,asked in companies like Amazon,Goldman Sachs and Nagarro.
6+
7+
Time Complexity:
8+
The goal is to complete this question in O(n).
9+
This solution is optimized by using bit manipulation. If we start at a value of 0 and XOR all the characters of both strings, we should return an end value of 0 if they are anagrams because there would be an even occurrence of all characters in the anagram.
10+
11+
Space Complexity:
12+
The space complexity of this approach is O(1).
13+
"""
14+
# Function to check whether two strings are anagrams of each other
15+
def are_anagrams(string1, string2):
16+
17+
# If two strings have different size we return False as they cannot be anagrams of each other
18+
if (len(string1) != len(string2)):
19+
return False
20+
# Variable to store the Xor Value
21+
xor_value = 0
22+
for i in range(len(string1)):
23+
xor_value = xor_value ^ ord(string1[i])
24+
xor_value = xor_value ^ ord(string2[i])
25+
26+
if(xor_value==0):
27+
return True
28+
else:
29+
return False
30+
31+
# Code To test The Function
32+
string1 = "thestringsareanagrams"
33+
string2 = "arethestringsanagrams"
34+
if(are_anagrams(string1, string2)):
35+
print("The two strings are anagram of each other")
36+
else:
37+
print("The two strings are not anagram of each other")
38+
39+

0 commit comments

Comments
 (0)