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
Use HashMap to store element frequencies or mappings. Iterate through array once to build map, then solve based on stored data. Common for two-sum and anagram problems.
Implementation
def twoSum(nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return []Complexity Analysis
Time Complexity
O(n)Space Complexity
O(n)Key Learning Points
HashMap for O(1) lookupsSingle pass solutionComplement/pairing pattern
Related Problems to Practice
Two SumValid AnagramGroup Anagrams
Complexity
Time:O(n)
Space:O(n)
Hints
- 1.What makes two strings anagrams?
- 2.Count character frequencies
- 3.Can you do it with a single pass?
Asked at
Google