You cannot change the line in O(N) , but you can do it with O(1) space complexity.
return line in one operation
Most likely it was reverse it in one-liner , since he did not even understand what an βoperationβ really is.
You can use std :: reverse to reverse the line in one line :
#include <string> #include <algorithm> int main() { std::string str = "Hello world!"; std::reverse(str.begin(), str.end()); std::cout << "reverse is: \"" << str << '\"' << std::endl; }
Output:
reverse is: "!dlrow olleH"
or you can use a simple loop for this:
for (size_t i=0; i<str.size()/2; ++i) std::swap(str[i], str[str.size()-1-i);
this, however, is O(N) runtime and O(1) space (like std::reverse ).
Usually, interviews with simple inverse string algorithm algorithms are not about some tricks; most likely, your interviewer wanted to see that such a cycle has been implemented. Also, do not forget that interviewers are also people, and sometimes they just make mistakes and ask for impossibility. Or they just wanted you to say that it is not possible to change the sequence in O(1) .
Pavel source share