Here is an algorithm counting occurrences of anagrams of one string (search_word) in the other (text):
#include<iostream>
#include<algorithm>
#include<string>
#include<deque>
using namespace std;
int main()
{
string text = "forxxorfxdofr";
string search_word = "for";
deque<char> word;
word.insert(word.begin(), text.begin(), text.begin() + search_word.size());
int ana_cnt = 0;
for (int ix = 3; ix <= text.size(); ++ix)
{
deque<char> temp = word;
sort(word.begin(), word.end());
if (string(word.begin(), word.end()) == search_word)
++ana_cnt;
word = temp;
word.pop_front();
word.push_back(text[ix]);
}
cout << ana_cnt << endl;
}
What's the complexity of this algorithm?
I think it's O(n) algorithm, where n is the length o text. This is because the amount of time needed to execute what is inside for loop is independent of the lenght of n. However, some think it is not O(n). They say the sorting algorithm also counts when computing complexity.
text.begin() + 3should probably better betext.begin() + search_word.length().mis bounded byn, i.e. m = O(n). Therefore O(nm log m) = O(n^2 log n). So yes, you are wrong. You’d be right for Θ, but O is an upper bound.