forked from narayancseian/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request narayancseian#59 from khushbu2k6/main
Create Determine whether two strings are anagram or not.py
- Loading branch information
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
43 changes: 43 additions & 0 deletions
43
Hashing/Determine whether two strings are anagram or not.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
# Function to check if `X` and `Y` are anagrams or not | ||
def isAnagram(X, Y): | ||
|
||
# if X's length is not the same as Y's, they can't be an anagram | ||
if len(X) != len(Y): | ||
return False | ||
|
||
# create an empty dictionary | ||
freq = {} | ||
|
||
# maintain the count of each character of `X` in the dictionary | ||
for i in range(len(X)): | ||
freq[X[i]] = freq.get(X[i], 0) + 1 | ||
|
||
# do for each character `y` of `Y` | ||
for i in range(len(Y)): | ||
|
||
# if `y` is found not in the dictionary, i.e., either `y` is not present | ||
# in string `X` or has more occurrences in string `Y` | ||
if not Y[i] in freq: | ||
return False | ||
|
||
# decrease the frequency of `y` on the dictionary | ||
freq[Y[i]] = freq[Y[i]] - 1 | ||
|
||
# if its frequency becomes 0, erase it from the dictionary | ||
if freq[Y[i]] == 0: | ||
del freq[Y[i]] | ||
|
||
# return true if the dictionary becomes empty | ||
return not freq | ||
|
||
|
||
if __name__ == '__main__': | ||
|
||
X = 'tommarvoloriddle' # Tom Marvolo Riddle | ||
Y = 'iamlordvoldemort' # I am Lord Voldemort | ||
|
||
if isAnagram(X, Y): | ||
print('Anagram') | ||
else: | ||
print('Not an Anagram') | ||
|