Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String reverse operation best time complexity: Is it O(n) or O(n/2)?

Tags:

java

algorithm

Below code snippet for String reverse

private static String reverseString(String originalString){
char arr[]= originalString.toCharArray();
char temp;

for(int i= 0,j=arr.length-1;i<(arr.length/2);i++,j--){

 temp=arr[i];
 arr[i]=arr[j];
 arr[j]=temp;
}
return new String(arr);

I have seen lot of discussion over the time complexity for the above String reverse where some have mentioned the complexity to be O(n/2) and some O(n).

I would like to understand which one would actually be the correct time complexity for the string reverse.

Any insight would be really helpful in assuaging the confusion here.

like image 213
java newbie Avatar asked Jun 29 '15 07:06

java newbie


People also ask

What is the time complexity of reversing a string?

We then use the charAt() function to create the string in a reverse order which is then returned. The time complexity of the function is O(N).

Can we reverse a string in O 1?

You cannot reverse a string in O(1) time, however, you can do so with O(1) space complexity. Most likely it was reverse it in one-liner , as it's not even clear what an "operation" is really is. or you may as well use a simple loop to do it: for (size_t i=0; i<str.

What is the complexity of reverse string in Java?

At the point characters in your String are reversed. This algorithm only requires one extra character of memory to facilitate the swapping of characters. The time complexity of this algorithm is O(n/2)I mean O(n) where n is the length of String.

What is the time complexity of reversing a string python?

Time Complexity of this approach is O ( N ) O(N) O(N) where N is the length of the string to be reversed.


2 Answers

Asymptotically there is no difference between O(n) and O(n/2). The difference between the two is constant.

If you want to compute the exact number of operations in the above code snippet, it would be more accurate to say it's 3n/2, since each iteration of the loop contains 3 operations. Of course you'll also have to add the conversion of the input String to a char array and vice versa, both of which also take linear time.

like image 181
Eran Avatar answered Oct 23 '22 04:10

Eran


Big O notation is used in the asymptotic analysis ( meaning in the long run )

This means that your all linear functions will have the same time complexity that is O(n), It does not matter that T(n) = n/1 or n/2 or n/3 because in the long run they will all have the same effect.

like image 23
Sumeet Avatar answered Oct 23 '22 03:10

Sumeet