One Pager Cheat Sheet
- Write a method
isAnagram(str1, str2)
to check if two strings are anagrams of each other, given that they contain only alphanumeric characters and have a length of up to 100000, with an expected time and space complexity of O(nlogn) and O(n), respectively. - We can use
lowercase
and sorting to efficiently determine if two strings, such asMary
andArmy
, are anagrams. - By
splitting
,sorting
andjoining
the characters in each string, we can easilycompare
theraw characters
present to determine if two strings areanagrams
. - This algorithm has an
O(n log n)
time complexity andO(n)
space complexity.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
37
}
var assert = require('assert');
​
function isAnagram(str1, str2) {
let a = str1.toLowerCase();
let b = str2.toLowerCase();
​
a = a.split('').sort().join('');
b = b.split('').sort().join('');
​
return a === b;
}
​
try {
assert.equal(isAnagram('Mary', 'Army'), true);
​
console.log('PASSED: ' + "`isAnagram('Mary', 'Army')` should return true");
} catch (err) {
console.log(err);
}
​
try {
assert.equal(isAnagram('cinema', 'iceman'), true);
​
console.log(
'PASSED: ' + "`isAnagram('cinema', 'iceman')` should return true"
);
} catch (err) {
console.log(err);
}
​
try {
assert.equal(isAnagram('jake', 'jay'), false);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.