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.
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).
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.
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.
Time Complexity of this approach is O ( N ) O(N) O(N) where N is the length of the string to be reversed.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With