Reverse a domain name string For an interview question, I was asked to do the following:


  Given a dot separated domain name, reverse the domain elements.


Here are a few input/output examples:

codereview.stackexchange.com -&gt; com.stackexchange.codereview
foo.bar -&gt; bar.foo
a.. -&gt; ..a


This was my proposed solution. I really feel like there's probably a better way to do this (in place?).

#include &lt;iostream&gt;
#include &lt;string&gt;

std::string
reverse(const std::string &amp;str)
{
    std::string rstr = str;
    std::reverse(rstr.begin(), rstr.end());
    int size = rstr.size();
    int start = 0;
    int end = 0;
    while (end != size + 1) {
        if (rstr[end] == '.' || end == size) {
            std::reverse(rstr.begin() + start, rstr.begin() + end);
            start = end + 1;
        }
        ++end;
    }
    return rstr;
}

int 
main()
{
    std::string examples[] = {
        "hello.world",
        "com.domain.something",
        "..a"
    };

    int size = sizeof(examples) / sizeof(examples[0]);
    for (int i = 0; i &lt; size; ++i) {
        std::cout &lt;&lt; examples[i] &lt;&lt; " -&gt; " &lt;&lt; reverse(examples[i]) &lt;&lt; std::endl;
    }

    return 0;
}
This looks quite fine to me. Granted, you make several passes over the entire string, but that doesn't matter much, as the time complexity remains \$O(n)\$, space complexity constant, and this is easy to read and understand.

You could reduce the number of passes by using extra storage, in which you could prepend the reversed segments. But due to the extra storage, such algorithm would not be better, it would be different. Whether one solution is better than the other depends on external constraints not stated in the problem. Talking about this is important at an interview, more important than whatever solution you gave.

In terms of the implementation, the only thing I would change is convert the main while loop to a for loop. The reason is that the start and end variables are only used inside the loop body, and the for loop would help confining them into that scope, which is a good thing, reducing the live time of those variables, and preventing accidental uses outside the loop.