That is O(n).
You swap elements n/2 times: (0 with n-1), (1 with n-2), ... (n/2 - 1 with n/2 + 1)
What is the time complexity of this "reverse words" algorithm? - Computer Science Stack Exchange
algorithm - How to reverse a string in O(1) complexity (runtime)? - Stack Overflow
What is the time complexity of reversing a string?
What is the time complexity of reverse() ?
This algorithm runs in linear time in the size of the input .
To see why try to count how many times you read/write to a position in the string. Note that asymptotically this is equal to the total running time.
Have you run the code?
If you reverse the array ['d', 'r', 'a', 'h', ' ', 's', 'i', ' ', 's', 'c'] you get the desired result of ['c', 's', ' ', 'i', 's', ' ', 'h', 'a', 'r', 'd']. If you then reverse the words you get ['s', 'c', ' ', 's', 'i', ' ', 'd', 'r', 'a', 'h'], which is not what you want.
You can't get better than an complexity for reversing an array of size
. If you want an explanation as to why this is the case, then we must be slightly more precise. Below I do the analysis for an easy to analyze implementation, not an inplace version. (The analysis is similar for an inplace version, and I think that you can work it out.)
Let's assume that the operations which have a cost are "reading a value from an array", "writing a value to an array", and "comparing two values". The input to our algorithm is an array input of size and the output is an array
output also of size , and we must ensure that when the algorithm terminates that
output[i] == input[n-i-1] where . (Take a minute and convince yourself that this is a correct description of the problem, and that the equality is correct for both even and odd values of
.) To make the analysis as simple as possible, we will assume that there is an array named
output of size just waiting for us, and that
output[i] == 0 for all .
Therefore, any algorithm must assign to output[i] the value input[n-i-1] for all possible values of
, unless
input[n-i-1] == 0, in which case no assignment needs to be made, as the correct value is already present. So one possible implementation would loop through the different values of
and check if
input[n-i-1] == 0 and continue when the condition was true and assign the value to output[i] when the condition was false.
If the input array is
0s then this implementation would perform exactly operations, one operation to get the value at
input[n-i-1] and one operation to compare it to 0. However, if there are no values of 0 in the input, then there are exactly operations performed,
of the operations are the same as before, but now there are
assignments of the value to the correct position in the output array (here we assume we don't need to read the value from the input array again). More generally if
0 occurs times in the input then there are exactly
operations performed.
Now this part is important: if we don't check the value, but instead just do the assignment then there are always operations, one to read from the input and one to write to the output. Checking the value each time to avoid an unnecessary copy does more work than not checking the value in the majority of cases. Since any algorithm which uses these operations must do at least this much work, you can't do better than
operations.
But what about other operations? For an inplace version you might consider an operation which swaps two values in the array swap(i, j). Such an operation allows you to reverse the array in operations (for even
), which is still
.
You cannot reverse a string in O(1) time, however, you can do so with O(1) space complexity.
reverse a string in single operation
Most likely it was reverse it in one-liner, as it's not even clear what an "operation" is really is.
You can use std::reverse algorithm to reverse a string 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 may as well use a simple loop to do it:
for (size_t i=0; i<str.size()/2; ++i)
std::swap(str[i], str[str.size()-1-i);
this is however is O(N) runtime, and O(1) space (just like std::reverse).
Usually interviews with simple reverse string algorithm questions isn't about some tricks, most likely your interviewer wanted to see that kind of loop implemented. Also, don't forget that interviewers are also humans and sometimes they simply make mistakes and ask for impossible. Or, they simply wanted you to say that it is not possible to reverse a sequence in O(1).
Reverse a string? Just iterate it from rbegin() to rend(). Or std::copy that range to a new string.
A "reversed string" is just the same as the original string, just read the other way.
I'm getting ready for an interview and practicing time complexity and I'm ok at recognizing the complexity for the code I've written myself but have a harder time when I throw in methods from the java library.
For example, I read that the method concat was similar to += and that concat time complexity was O(n^2). So if I reverse a string with the code below does that mean my time complexity is O(n^2)? With a space complexity of O(n) since? Where n is the length of the string.
String str="hello"
String s="";
for(int i =str.length()-1; i>=0;i--){
s+=str.substring(i,i+1);
}With this code is the space complexity O(n) and the time complexity O(n)? Where n is the length of the string.
String str="hello";
char[] cArr = str.toCharArray();
int i =0;
int j = cArr.length-1;
char temp;
while(i<j){
temp =cArr[i];
cArr[i]=cArr[j];
cArr[j]=temp;
i++;
j--;
}
str=String.valueOf(cArr);