A program I'm working on converts an array of integers to a string using string builder. I'm trying to determine the time complexity of this approach.
Check out: https://stackoverflow.com/a/7156703/7294647
Basically, it's not clear what the time complexity is for StringBuilder#append
as it depends on its implementation, so you shouldn't have to worry about it.
There might be a more efficient way of approaching your int[]-String conversion depending on what you're actually trying to achieve.
If the StringBuilder
needs to increase its capacity, that involves copying the entire character array to a new array. You can avoid this by initially setting the capacity so it won't have to do this. (This should be easy since you know the length of the int
array and the maximum number of characters in the String
representation of an int
.)
If you avoid the need to increase the capacity, the complexity would seem to just be O(n). When you append, you're just copying the character array from the String
to the end of the character array in the StringBuilder
.
(Yes, it depends on the implementation, but it would be a rather poor implementation of StringBuilder
if it couldn't append in O(n) time.)
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