Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
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.
Example 1: Input: s = “anagram”, t = “nagaram” Output: true
Example 2:
Input: s = “rat”, t = “car” Output: false
Sorting Method
Turn the strings into lists, sort them, and check if the sorted lists are identical.
- Time complexity:
- Space complexity:
Hashing Map
Build hashmaps where:
Key | Value |
---|---|
‘character’ | ‘count’ |
a | 3 |
n | 1 |
etc… |
Compare that the keys and counts for each key are the same.
- Time complexity:
- Space complexity:
Notes:
- Dictionaries in Python are implemented as hashmaps
sCounter.get(s[i],0)
deals with the case that there is nothing at that key; if there is nothing, it uses a default value of0
.