Valid Anagram Visualizer & Step-by-Step Algorithm Solution

Check if two strings contain identical character frequency distributions.

Category: arrays | Difficulty: Easy

Tags: Hash Map, String, Frequency

Valid Anagram

String s
i
a
0
n
1
a
2
g
3
r
4
a
5
m
6
String p
n
0
a
1
g
2
a
3
r
4
a
5
m
6
Character Frequency Map
(Empty Map)
100%
Initialization
1/39
Explanation

Starting isAnagram function.

Source Code
1function isAnagram(s, p) {
2 const map = new Map();
3 for (let i = 0; i < s.length; i++) {
4 map.set(s[i], (map.get(s[i]) || 0) + 1);
5 }
6 for (let j = 0; j < p.length; j++) {
7 if (!map.has(p[j])) return false;
8 const count = map.get(p[j]) - 1;
9 if (count === 0) map.delete(p[j]);
10 else map.set(p[j], count);
11 }
12 return map.size === 0;
13}