Given two strings s
and t
, write a function to determine if t
is an anagram of s
.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
To determine if t
is an anagram of s
:
We can implement this using two strategies:
The hash map strategy is more efficient because sorting has a time complexity of O(n log n)
, while using a hash map has a linear time complexity of O(n)
.
We’ll implement the hash map strategy.
def isAnagram(s: str, t: str) -> bool:
# Early return if lengths differ
if len(s) != len(t):
return False
# Create frequency dictionaries for both strings
count_s = {}
count_t = {}
for char in s:
count_s[char] = count_s.get(char, 0) + 1
for char in t:
count_t[char] = count_t.get(char, 0) + 1
# Compare frequency dictionaries
return count_s == count_t
s
and t
are different, immediately return False
.s
and t
.t
is an anagram of s
; otherwise, it is not.O(n)
, where n
is the length of the strings. We iterate over each string once to build the frequency dictionaries and then perform a comparison of the dictionaries, which is also linear in time.O(1)
assuming the character set is fixed (e.g., ASCII or Unicode). The dictionaries will have a space complexity proportional to the number of unique characters in the strings.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?