EasyLeetCode #242Arrays & Hashing
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.
Constraints
1 <= s.length, t.length <= 5 * 10^4, s and t consist of lowercase English letters
Examples
Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false
Solution
Approach
Count character frequencies in both strings and compare. Use a hash map or array of size 26 for lowercase letters.
def isAnagram(s, t):
if len(s) != len(t):
return False
return Counter(s) == Counter(t)Complexity
Time:O(n)
Space:O(1)
Hints
- 1.What makes two strings anagrams?
- 2.Count character frequencies
- 3.Can you do it with a single pass?
Asked at
Google