Check if two strings are anagrams of each other.
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.
Examples
Input: s = "anagram", t = "nagaram"
Output: true
Explanation: Both strings contain the exact same character counts.
Input: s = "rat", t = "car"
Output: false
Explanation: The characters and their counts do not match.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
An anagram contains the exact same frequency of each character.
š” Hint 2:
First check if lengths match: s.length === t.length.
š” Hint 3:
Use a frequency array of size 26. Increment for s and decrement for t. Every entry must end at 0.
Editorial & Approach
Problem Overview & Intuition
Two strings are anagrams if and only if their character frequencies are identical. Using a 26-element array for lowercase English letters, increment counts for characters in s and decrement for t in a single pass.
Step-by-Step Approach
- If
s.length !== t.length, returnfalse. - Allocate frequency array of size 26 filled with 0.
- Iterate
ifrom 0 tos.length - 1: - Increment
count[s.charCodeAt(i) - 97]++and decrementcount[t.charCodeAt(i) - 97]--. - Return
trueif all entries incountare 0; otherwisefalse.
Optimal Implementation (JavaScript)
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const count = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
count[s.charCodeAt(i) - 97]++;
count[t.charCodeAt(i) - 97]--;
}
return count.every((c) => c === 0);
}
Complexity Analysis
Time Complexity
O(N) ā single pass of length N.
Space Complexity
O(1) ā fixed array of size 26.
Edge Cases & Corner Traps Handled
- Different length strings: false.
- Identical strings: true.
- Same letters different frequencies: "aab" and "abb" -> false.