Problem Statement: here
PS Goal:
We are given two strings s and t. We have to answer whether string t can be formed strictly using the letters in string s.
Solution:
Two strings are anagrams if the have the same characters with same frequency. The order of the characters does not matter.
Since we only have to check if the characters match in both the strings, my immediate thought was to sort both the strings and compare the sorted strings. If they are identical, then we can return true saying that the strings are anagrams. Else, they are not anagrams of each other.
def isAnagram(s, t):
return sorted(s) == sorted(t)
Without using the sorted() function we can break it down and get the desired output as such:
def isAnagram(s, t):
if len(s) != len(t):
return False
count = {}
for ch in s:
count[ch] = count.get(ch, 0) + 1
for ch in t:
if ch not in count:
return False
count[ch] -= 1
if count[ch] < 0:
return False
return True
- Here, we give an inital check that if the length of the strings are not equal, we can say that they are not anagrams.
- Then we get each character in string s and store it in count[]. We iterate through string t and if a character is not in count[] then we return false.
- Only the strings that match in characters are anagrams and the function returns true.
Top comments (0)