Created
May 29, 2020 16:26
-
-
Save pratik7368patil/108a915c1bc32a2fd42157b29473c9f7 to your computer and use it in GitHub Desktop.
Check if two strings are Anagram
This file contains hidden or 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
# this problem can be solve using Hashmap with O(N) time | |
def check_anagram(s1, s2): | |
if len(s1) != len(s2): # check for base case | |
return False | |
counter = [0]*26 # each character of string is between a-z | |
n = ord("a") # integer value of "a" that is 97 | |
for i in range(len(s1)): | |
counter[ord(s1[i]) - n] += 1 # update counter at each character | |
counter[ord(s2[i]) - n] -= 1 # decrease counter at each character | |
for x in counter: # check if characters are same or not | |
if x != 0: | |
return Flase | |
return True # if all characters are same | |
s1 = "hackyourcode" # first string | |
s2 = "codehackyour" # second String | |
print(check_anagram(s1,s2)) | |
# the output will be "True" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment