I am reading "Cracking The Coding Interview", and came upon a question that asks to write an algorithm that checks to see if one string is a permutation of another. The book's solution doesn't explain the time complexity(go figure), so I was wondering what it would actually be for the function below.
function permutations(a, b) {
if (a.length !== b.length) {
return false;
}
const aSorted = a
.split("")
.sort((a, b) => a.localeCompare(b))
.join("");
const bSorted = b
.split("")
.sort((a, b) => a.localeCompare(b))
.join("");
return aSorted === bSorted;
}
The split
and join
functions must be O(n), and I believe the built in sort
function is O(n log n) (which I don't even understand). Since O(n log n) is worse than O(n), do we just forget about the other operations?