If you have ever attended a JavaScript interview, solved coding challenges on platforms like LeetCode, HackerRank, or practiced Data Structures and Algorithms (DSA), there is a high chance you have encountered an Anagram problem.
At first glance, the question looks very simple.
You are given two strings and asked whether they are anagrams of each other.
Many beginners immediately start comparing characters one by one, but that approach quickly becomes difficult when the strings become larger.
In this article, we will understand:
- What an anagram is
- How to identify an anagram
- How to solve the problem efficiently in JavaScript
- Why we use an object to count characters
- Common mistakes developers make
- Interview tips related to anagrams
By the end of this article, you will be able to solve most string anagram interview questions with confidence.
What is an Anagram?
An anagram is a word or phrase formed by rearranging the letters of another word while using all characters exactly the same number of times.
Let's look at a simple example.
hello
ollheBoth strings contain:
h = 1
e = 1
l = 2
o = 1The characters are simply arranged in a different order.
Therefore:
hello === ollheThey are anagrams.
Real Life Example
Imagine you have a box containing five letter tiles:
H E L L OYou shuffle those tiles and create:
O L L H EEven though the arrangement changed, the tiles inside the box remain exactly the same.
An anagram works in the same way.
The order does not matter.
Only the characters and their quantities matter.
Understanding the Problem Statement
Suppose we have:
let stringOne = "hello";
let stringTwo = "ollhe";We need to determine whether both strings contain:
- The same characters
- The same number of occurrences of each character
If both conditions are true, return:
trueOtherwise:
falseConditions Required to Solve the Problem
Before writing code, let's think logically.
Condition 1: Length Must Be Equal
Consider:
hello
hellooThe lengths are different.
5 !== 6These strings can never be anagrams.
Therefore our first check should always be:
if(string1.length !== string2.length)This immediately eliminates invalid cases.
Condition 2: Character Frequency Must Match
Consider:
hello
holleCharacter count:
h = 1
e = 1
l = 2
o = 1Both strings contain the same characters with identical frequencies.
Now consider:
hello
helolxCharacter count becomes:
x = 1The extra character breaks the condition.
Therefore frequency comparison is required.
Efficient Solution Using Frequency Counter Pattern
One of the most popular DSA techniques for solving anagram problems is called the Frequency Counter Pattern.
Instead of repeatedly searching through strings, we store character counts inside an object.
For example:
{
h:1,
e:1,
l:2,
o:1
}This allows us to perform lookups very quickly.
JavaScript Solution
function sol(string1, string2) {
if (string1.length !== string2.length) {
return false;
}
let obj = {};
for (let value of string1) {
obj[value] = (obj[value] || 0) + 1;
}
for (let value2 of string2) {
if (!obj[value2]) {
return false;
}
obj[value2] -= 1;
}
return true;
}
const result = sol("hello", "ollhe");
console.log(result);Output:
trueStep-by-Step Dry Run
Let's understand exactly what happens inside the code.
Input:
hello
ollheStep 1: Length Check
5 === 5Pass.
Execution continues.
Step 2: Create Empty Object
let obj = {};Current state:
{}Step 3: Count Characters of First String
Loop:
for(let value of string1)After processing:
{
h:1,
e:1,
l:2,
o:1
}This object stores the frequency of every character.
Step 4: Iterate Through Second String
Current string:
ollheFirst character:
oExists.
Decrease count:
{
h:1,
e:1,
l:2,
o:0
}Second character:
lDecrease:
{
h:1,
e:1,
l:1,
o:0
}Continue until all characters become:
{
h:0,
e:0,
l:0,
o:0
}Since every character matched successfully:
return true;Why Does This Approach Work?
Think about a supermarket inventory system.
Suppose a store has:
Apple = 10
Banana = 5
Orange = 7Every sale decreases inventory.
Similarly:
- First string adds character counts.
- Second string removes character counts.
If everything balances perfectly, the strings are anagrams.
Time Complexity Analysis
Building Frequency Object
O(n)Checking Second String
O(n)Total:
O(n)This is much better than many beginner approaches that use nested loops.
Space Complexity
We store character frequencies inside an object.
O(n)Space complexity is linear relative to the number of unique characters.
Common Mistakes Beginners Make
Mistake 1: Comparing Sorted Strings Without Understanding
Many developers write:
str1.split('').sort().join('')While it works, interviews often want you to understand frequency counting.
Don't rely only on sorting.
Mistake 2: Ignoring Length Check
Without length validation:
hello
hellooYou waste extra processing time.
Always check lengths first.
Mistake 3: Forgetting Duplicate Characters
Consider:
hello
helooBoth contain similar characters.
However:
l = 2versus
o = 2The frequencies differ.
Therefore:
falseAlternative Solution Using Sorting
Another common approach is:
function isAnagram(str1, str2){
return str1
.split('')
.sort()
.join('') ===
str2
.split('')
.sort()
.join('');
}Example:
console.log(
isAnagram("hello", "ollhe")
);Output:
trueWhich Solution Is Better?
Sorting Approach
Time Complexity:
O(n log n)because sorting is involved.
Frequency Counter Approach
Time Complexity:
O(n)Faster and usually preferred during interviews.
Interview Tip
When an interviewer asks an anagram question, they are often testing:
- String manipulation skills
- Object usage
- Frequency counting
- Time complexity knowledge
- Problem-solving ability
A good answer should include:
- Length validation
- Frequency counting
- Complexity explanation
Many candidates write working code but fail to explain why it works.
Always explain your thought process.
Real Project Usage
Although the exact anagram problem may not appear daily in production code, the underlying frequency-counting technique is used in many real applications.
Examples include:
- Search engines
- Text processing systems
- Spell checkers
- Word games
- Data validation
- Pattern matching algorithms
Learning this problem teaches a reusable DSA pattern.
Frequently Asked Questions (FAQs)
What is an anagram in JavaScript?
An anagram is a word or string that contains exactly the same characters and frequencies as another string but arranged differently.
Why do we use an object in an anagram problem?
Objects allow us to store character frequencies and perform fast lookups.
Is sorting a valid solution?
Yes. However, sorting takes O(n log n) time, while the frequency counter approach takes O(n).
Which approach is preferred in interviews?
Most interviewers prefer the frequency counter solution because it demonstrates a better understanding of time complexity.
Can an anagram contain spaces?
Yes. In advanced versions of the problem, spaces and special characters are often ignored after preprocessing the strings.
Why Interviewers Love Anagram Questions
Many beginners think an anagram question is simply about checking whether two words contain the same letters.
However, interviewers are usually testing something much deeper.
When an interviewer asks an anagram question, they are often evaluating:
Problem-solving ability
Logical thinking
Understanding of objects and hash maps
Time complexity knowledge
Ability to optimize a solution
Imagine two candidates.
The first candidate immediately writes code without thinking.
The second candidate pauses and says:
"Before writing code, I would first check whether both strings have the same length. Then I would count the frequency of each character and compare them."
The second answer instantly shows structured thinking.
That is exactly what interviewers want to see.
The goal is not just to get the correct answer.
The goal is to demonstrate how you approach problems.
The Brute Force Approach (How Most Beginners Start)
Before learning the frequency counter pattern, many developers try solving the problem using nested loops.
For example:
function isAnagram(str1, str2){
if(str1.length !== str2.length){
return false;
}
for(let i = 0; i < str1.length; i++){
let found = false;
for(let j = 0; j < str2.length; j++){
if(str1[i] === str2[j]){
found = true;
break;
}
}
if(!found){
return false;
}
}
return true;
}
At first glance, this solution seems reasonable.
But there is a problem.
For every character in the first string, we are searching through the second string.
If the string becomes very large, performance starts decreasing.
Why Is It Slow?
Suppose we have:
1000 characters
The outer loop runs:
1000 times
The inner loop may also run:
1000 times
Total operations become:
1000 × 1000
Which gives:
O(n²)
This is why experienced developers prefer the frequency counter pattern.
Understanding the Frequency Counter Pattern
The frequency counter pattern is one of the most important techniques in Data Structures and Algorithms.
The idea is simple.
Instead of repeatedly searching for values, we count how many times each value appears.
Think about a classroom.
Suppose a teacher wants to know how many students chose each favorite programming language.
Instead of asking the same question repeatedly, the teacher creates a tally sheet.
JavaScript = 15
Python = 12
Java = 8
C++ = 5
Now the information is available instantly.
The frequency counter pattern works in the same way.
Frequency Counter Using JavaScript Object
let obj = {};
for(let char of "hello"){
obj[char] = (obj[char] || 0) + 1;
}
console.log(obj);
Output:
{
h:1,
e:1,
l:2,
o:1
}
Now we know exactly how many times each character appears.
Visual Representation of the Solution
Let's visualize the process.
String:
hello
Character count table:
| Character | Frequency |
|---|---|
| h | 1 |
| e | 1 |
| l | 2 |
| o | 1 |
Now we process:
ollhe
Step by step:
| Character | Remaining Count |
|---|---|
| o | 0 |
| l | 1 |
| l | 0 |
| h | 0 |
| e | 0 |
All counts become zero.
Therefore:
true
The strings are anagrams.
Case-Sensitive vs Case-Insensitive Anagrams
This is a common interview follow-up question.
Consider:
Hello
hello
Should this return:
true
or
false
The answer depends on requirements.
By default JavaScript treats:
H !== h
Therefore:
false
Making It Case Insensitive
Before comparison:
string1 = string1.toLowerCase();
string2 = string2.toLowerCase();
Now:
Hello
hello
becomes:
hello
hello
Result:
true
Handling Spaces in Anagram Problems
Real interview questions are often more challenging.
Example:
rail safety
fairy tales
These are actually anagrams.
But spaces create a problem.
Before comparison we should remove them.
string1 = string1.replace(/\s/g, "");
string2 = string2.replace(/\s/g, "");
Now both strings can be compared correctly.
Handling Special Characters
Consider:
Dormitory
Dirty room!
They are anagrams.
But the exclamation mark causes issues.
We can clean the strings first.
string1 = string1
.toLowerCase()
.replace(/[^a-z0-9]/g, "");
string2 = string2
.toLowerCase()
.replace(/[^a-z0-9]/g, "");
This removes:
Spaces
Special characters
Punctuation marks
Now comparison becomes much more reliable.
Production-Ready Anagram Function
Let's combine everything we have learned.
function isAnagram(str1, str2){
str1 = str1
.toLowerCase()
.replace(/[^a-z0-9]/g, "");
str2 = str2
.toLowerCase()
.replace(/[^a-z0-9]/g, "");
if(str1.length !== str2.length){
return false;
}
let counter = {};
for(let char of str1){
counter[char] = (counter[char] || 0) + 1;
}
for(let char of str2){
if(!counter[char]){
return false;
}
counter[char]--;
}
return true;
}
Example:
console.log(
isAnagram(
"Dormitory",
"Dirty room!"
)
);
Output:
true
This version is much closer to what you would use in a real application.
Real-World Applications of Anagrams
Many developers assume anagrams only appear in coding interviews.
That is not completely true.
The same character-counting technique is used in many real systems.
Spell Checking Systems
Tools like Microsoft Word and Google Docs analyze words and character patterns.
Search Engines
Search engines use various matching algorithms to identify related words and search terms.
Word Games
Games like:
Scrabble
Word Hunt
Crossword generators
often rely on anagram-like logic.
Text Analysis Software
Applications that analyze large amounts of text frequently count character and word frequencies.
Plagiarism Detection
Some text comparison systems use pattern matching techniques that are conceptually similar to frequency counting.
Practice Questions
Try solving these yourself before looking at solutions.
Question 1
listen
silent
Expected Output:
true
Question 2
triangle
integral
Expected Output:
true
Question 3
apple
papel
Expected Output:
true
Question 4
hello
world
Expected Output:
false
Question 5
Astronomer
Moon starer
Expected Output:
true
Try solving all of these using the frequency counter pattern without using the sort() method.
DSA Takeaway From This Problem
A lot of beginners focus only on getting the answer.
Experienced developers focus on recognizing patterns.
The biggest lesson from this problem is not the word "anagram."
The real lesson is learning the Frequency Counter Pattern.
Once you master this pattern, you can solve many problems involving:
Character counting
Duplicate detection
Array comparison
Word frequency analysis
Data validation
This single technique appears again and again in JavaScript interviews and real-world applications.
The anagram problem is simply one of the best places to learn it.

0 Comments