Skip to content

Commit

Permalink
Merge pull request narayancseian#59 from khushbu2k6/main
Browse files Browse the repository at this point in the history
Create Determine whether two strings are anagram or not.py
  • Loading branch information
narayancseian authored Oct 12, 2022
2 parents cb6f051 + cfdb3c7 commit 9344d3e
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions Hashing/Determine whether two strings are anagram or not.py
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')

0 comments on commit 9344d3e

Please sign in to comment.