Search code examples
javastring

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


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)?


Solution

  • 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).