Preface: This is not a homework question. I’m going through an algos book in Python.
If I have the following code to solve an anagram.
Public bool anagram (string a, string b) {
return sort(a) == sort(b);
}
Let’s say the sorting algorithm is merge sort which is O(n log n). Since I have to do it twice does the time complexity become O(n^2 log n)?
No, since you need to do it a constant number of times, the complexity remains
O(n log n).Note that there is one more operation that you need to perform – namely, comparing strings. However, it’s
O(n), andO(n + n log n)remainsO(n log n).Also note that your
nis “underdefined”: you should say thatnismax(a.length, b.length)