Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of String.toCharArray(), O(n) or O(1)

Tags:

java

string

Suppose you want to convert a String of length n to a character array of length n.

char [] chArray = someString.toCharArray();

What is the computation complexity?O(n) or O(1) ( n: length of someString)

I am under the impression that all it does is to allocate memory of size n*sizeof(char) and make a copy of that string to that location. So copying n cells of memory takes O(n) time. Is it ?

or it could be O(1), ( simple pointer relocation or as mentioned here)?

like image 586
C graphics Avatar asked Mar 26 '14 21:03

C graphics


People also ask

What is string toCharArray?

The java string toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string. Syntax : public char[] toCharArray() Return : It returns a newly allocated character array.

What is toCharArray used for?

The Java toCharArray() method is used to convert a sequence of characters stored in a string to an array of chars. In this tutorial, we covered how to use the toCharArray() method in Java. You now have the knowledge you need to convert strings to char arrays in Java using toCharArray().


2 Answers

The answer is linear time.

Think of it as copying single char and putting it into an array. It depends on number of elements so it's O(n).

like image 98
Piotrek Hryciuk Avatar answered Nov 14 '22 23:11

Piotrek Hryciuk


It's linear time; it does the copy, and copies take linear time. (The constant factor might be quite low, but it's still linear overall.)

like image 20
Louis Wasserman Avatar answered Nov 15 '22 01:11

Louis Wasserman