Note: I'm aware of this existing post which is similar. However, it does not address all my questions sufficiently.
I have the following three functions, all of which do the same thing: reverse a domain name string.
std::string reverse_domain(const std::string& s) {
std::stringstream ss(s);
std::string segment;
std::vector<std::string> breakList;
while (std::getline(ss, segment, '.')) {
breakList.push_back(segment);
}
std::string result;
auto size = breakList.size();
for (int i = size - 1; i >= 0; --i) {
result += breakList[i];
if (i != size - 1) {
result += ".";
}
}
return result;
}
std::string reverse_domain2(const std::string& s) {
std::string result;
auto index = 0;
for (const auto& c : s) {
if (c == '.') {
index = 0;
result.insert(result.begin() + index, '.');
continue;
}
result.insert(result.begin() + index, c);
index++;
}
return result;
}
std::string reverse_domain3(std::string& copy) {
std::reverse(copy.begin(), copy.end());
auto start = 0;
auto size = copy.size();
for (auto i = 0; i <= size; i++) {
if (copy[i] != '.' && i != size) continue;
std::reverse(copy.begin() + start, copy.begin() + i);
start = i + 1;
}
return copy;
}
My question is, what is the time complexity of all of these?
My educated guesses are:
For
reverse_domain
: \$O(n) + O(n^2) + ?\$. The reasoning behind this is that I assume thegetline
loop is \$O(n)\$, and I assume appending to a string is \$O(n)\$, hence why I assume thefor
loop is \$O(n^2)\$. The last remaining piece is actually creating the string stream, hence the?
I have.For
reverse_domain_2
: \$O(n^2)\$. The reasoning behind this is thatinsert
is linear time, and so the whole for loop would just be \$O(n^2)\$.For
reverse_domain_3
: \$O(n) + O(n^2)\$. The reasoning behind this is that reversal is linear time. And in the for loop, there's another reversal, hence \$O(n^2)\$. However, since its only reversing a piece of the string, I'm not too sure.
Are all these assumptions and time complexities correct?
I timed the performance of each of these methods on a multivariate plot, where the x axis is the length of the string, the y axis is the number of "."
characters, and the z axis is the duration.
As you can see, reverse_domain
is by far the slowest, and the other two are similar, with reverse_domain_3
being the fastest. However, I'm not exactly too sure why this is. I'm also not sure how to (or if I should) express the time complexity in terms of just the string length, or the length as well as the number of "."
characters?
Thanks for any explanation(s).
reverse_domain2()
: What is the result ofresult.begin() + index
immediately afterindex = 0;
? \$\endgroup\$