Top Interview 150
The Valid Anagram problem is a straightforward challenge involving string manipulation and character counting. Letβs solve LeetCode 242: Valid Anagram step by step.
π Problem Description
Given two strings s and t:
- Return
trueiftis an anagram ofs. - Otherwise, return
false.
An anagram is a word or phrase formed by rearranging the letters of another. Both strings must have the same characters in the same frequencies.
π‘ Examples
Example 1
Input: s = "anagram", t = "nagaram"
Output: true
Explanation: Both strings have the same characters with the same frequencies.
Example 2
Input: s = "rat", t = "car"
Output: false
Explanation: The characters in `t` are not the same as in `s`.
π JavaScript Solution
We can efficiently solve this problem by counting the frequency of characters in both strings and comparing the counts.
Implementation
var isAnagram = function(s, t) {
if (s.length !== t.length) return false;
const charCount = {};
for (let char of s) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (let char of t) {
if (!charCount[char]) return false;
charCount[char]--;
}
return true;
};
π How It Works
-
Count Characters in
s:- Use a hash map (
charCount) to track the frequency of each character ins.
- Use a hash map (
-
Subtract Characters in
t:- For each character in
t, decrement its count incharCount. - If a character in
tis missing or its count becomes negative, returnfalse.
- For each character in
-
Return True:
- If all characters match and their counts balance, return
true.
- If all characters match and their counts balance, return
π Complexity Analysis
-
Time Complexity:
O(n), where n is the length of s (or t).- Each character is processed once.
Space Complexity:
O(1), as the hash map stores at most 26 entries for lowercase English letters.
π Dry Run
Input: s = "anagram", t = "nagaram"

Output: true
Follow-Up: Unicode Characters
For inputs containing Unicode characters, the solution can be adapted as follows:
- Instead of assuming lowercase English letters, allow any character as a key in the hash map.
- This approach is already supported by the above implementation, as JavaScript hash maps (
{}orMap) can store any string as a key.
β¨ Pro Tips for Interviews
- Discuss Sorting Approach:
- An alternative solution involves sorting both strings and comparing them.
- Time Complexity:
O(nlogn)due to sorting.
var isAnagram = function(s, t) {
return s.split("").sort().join("") === t.split("").sort().join("");
};
`
- Clarify Edge Cases:
- Different lengths:
s = "abc",t = "abcd". - Empty strings:
s = "",t = "".
- Different lengths:
π Learn More
Check out the full explanation and code walkthrough on my previous Dev.to post:
π Word Pattern - JavaScript Solution
Whatβs your preferred method to solve this problem? Letβs discuss! π

Top comments (1)
Follow Me on GitHub π
If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.
Don't forget to follow for more updates!