I am aware that the append() operation for StringBuffer takes O(1) time and it avoids the overhead of creating multiple copies of String objects as compared to String concatenation.
What about insert(int offset, char c)?
I need to repeatedly call this operation so as to add in new characters one by one in a reversed order to the StringBuffer object. For example,
StringBuffer sb = new StringBuffer();
sb.insert(0, 'c');
sb.insert(0, 'b');
sb.insert(0, 'a');
System.out.println(sb.toString()); //prints out "abc";
In an ideal situation, each insert(0, c) is supposed to be O(1) if internally that StringBuffer object looks like a linked list of characters. I wish to confirm if this is really the case.
Each time you append the StringBuilder it checks if the builder array is filled, if required copies the contents of original array to new array of increased size. So the space requirement increases linearly with the length of String. Hence the space complexity is O(n) .
It is O(1) when appending single characters. A StringBuilder is like an ArrayList. When you append a single item the cost is O(1). Appending a string is like calling addAll()--the cost is proportional to the length of the string / the number of items being added.
So we have created an object “obj” of the StringBuilder class. Next, we are appending the input string “str” using the append() method. The reverse() method is then called using obj and the result is returned. The time complexity of the code will be O(N).
For String, StringBuffer, and StringBuilder, charAt() is a constant-time operation. For StringBuffer and StringBuilder, deleteCharAt() is a linear-time (i.e. O(n)) operation, and NOT constant time operation.
The insert
operation on a StringBuffer
is O(n). This is because it must shift up to n
characters out of the way to make room for the element to be inserted.
"bc"
insert(0, 'a') => "_bc" => "abc"
You can get around this by not using insert
. You can iterate the letters in the reverse order, and then you can call the O(1) append
method.
The StringBuffer
class is a subclass of AbstractStringBuilder
, which defines a char[]
to hold the characters. It uses System.arraycopy
to move the existing characters out of the way on a call to insert
.
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