Valid Anagram
HashingStrings
EasyLeetCode #242
Problem Statement
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
String s:
a
n
a
g
r
a
m
String t:
n
a
g
a
r
a
m
Character Frequencies:
a×3
n×1
g×1
r×1
m×1
✓ Characters match - Valid Anagram!
Input: s = "anagram", t = "nagaram"
Output: true
Explanation:
- Both strings contain the same characters with the same frequencies
- Each letter appears the same number of times in both strings
- 't' can be formed by rearranging letters in 's'
Key Properties
- • Character frequency must match exactly
- • Order of characters doesn't matter
- • Case sensitive comparison
- • Can use array or hash map for counting
- • Both strings must be same length to be anagrams
Constraints
- • 1 ≤ s.length, t.length ≤ 5 × 10⁴
- • s and t consist of lowercase English letters
Solution Explanation
The solution uses a character frequency counting approach to determine if two strings are anagrams. By definition, anagrams must contain exactly the same characters with the same frequencies.
Key Steps
- Check if both strings have the same length
- Create a data structure to store character frequencies
- Count frequencies of characters in first string
- Verify frequencies match using second string
- Ensure all character counts are zero
Time & Space Complexity
- Time: O(n) where n is string length
- Space: O(1) since we only store 26 letters
- Single pass through each string
- Fixed size array/map for frequency counting
Starting anagram check...
String s:
a
n
a
g
r
a
m
String t:
n
a
g
a
r
a
m
Character Count Map:
Valid Anagram Solutions