Skip to content

Instantly share code, notes, and snippets.

@sahasourav17
Created January 14, 2022 16:49
Show Gist options
  • Save sahasourav17/6f055424cb3e658cff0a5b626593fd0f to your computer and use it in GitHub Desktop.
Save sahasourav17/6f055424cb3e658cff0a5b626593fd0f to your computer and use it in GitHub Desktop.
#Function to check two strings are anagrams or not
def anagrams(s1,s2):
"""
we first check if both strings have the same length
because if they're not it's impossible for them to
be anagrams.
"""
if len(s1) != len(s2):
return False
freq_1,freq_2 = {},{}
#creating hash table for first string
for ch in s1:
if ch in freq_1:
freq_1[ch] += 1
else:
freq_1[ch] = 1
#creating hash table for second string
for ch in s2:
if ch in freq_1:
freq_2[ch] += 1
else:
freq_2[ch] = 1
#comparing two hash tables with each other
for key in freq_2:
if key not in freq_1 or freq_1[key] != freq_2[key]:
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment