Apply frequency counters to determine whether two strings are anagrams.
Use the editor below to decide whether both strings contain exactly the same characters with exactly the same frequencies. Character order does not matter.
Count repeated letters
Check for different lengths early and count every occurrence of each letter.
Submit your implementation when it passes the examples.
Given two lowercase strings s and t, return true when t is an anagram of s.
An anagram uses every character from the original string exactly once, but the order may change.
1 ≤ s.length, t.length ≤ 50,000Results appear here after a run.
First reject strings with different lengths. Count every character in the first string, then scan the second string and consume one saved occurrence at a time.
If a required character has no remaining count, the strings cannot be anagrams. Matching lengths and a successful second pass mean every character was paired. “Empty” in the figure means no occurrences remain; the code can leave zero-valued entries in the map.
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const counts = new Map();
for (const character of s) {
counts.set(character, (counts.get(character) ?? 0) + 1);
}
for (const character of t) {
const remaining = counts.get(character) ?? 0;
if (remaining === 0) return false;
counts.set(character, remaining - 1);
}
return true;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | Average O(n) | Each character in both equal-length strings is processed once. |
| Auxiliary space | O(k) | The map stores k distinct letters. With this exercise’s 26 lowercase English letters, that is bounded by a constant. |