6

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

Community
  • 1
  • 1
C graphics
  • 7,308
  • 19
  • 83
  • 134

2 Answers2

7

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

Piotrek Hryciuk
  • 785
  • 10
  • 23
1

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

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413