Date and Time: Jul 13, 2024, 16:50 (EST)
Link: https://leetcode.com/problems/valid-anagram/
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
Explanation:
Edge case:
Input: s = "a", t = "ab"
Output: false
-
1 <= s.length, t.length <= 5 * 10^4
-
s
andt
consist of lowercase English letters.
Just build a hashmap to store s
, then loop over t
to decrement each element's occurence in the hashmap. And check if all elements' occurences in the hashmap are reset to 0
(which means s, t
are valid anagram).
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
sMap = {}
for i in s:
sMap[i] = 1 + sMap.get(i, 0)
for i in t:
if i in sMap:
sMap[i] -= 1
return max(sMap.values()) == 0
Time Complexity:
Space Complexity: