0

What is the run time (with regard to Big O) of the Arrays.toString() method in Java?

e.g.

String sort(String x){
char[] xArray = x.toCharArray();
Arrays.sort(xArray);
return Arrays.toString(xArray);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Joanna
  • 13
  • 1
  • 6
  • Just look at the [source code of the method](http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/be44bff34df4/src/share/classes/java/util/Arrays.java). – Turing85 Jan 03 '20 at 19:32
  • Wouldn't this completely depend on the Array passed? – Nexevis Jan 03 '20 at 19:35
  • By "runtime" do you mean the time it takes to run? Are you asking about the performance? – mypetlion Jan 03 '20 at 19:42
  • Should be O(n) to get through all characters (with some low-level modifications possible). In your example it should not make any performance issue since sort is O(n log n) which is slower, so the total complexity will be O(n log n) – Anatoliy R Jan 03 '20 at 20:33
  • @mypetlion I mean with regards to Big O time! I will clarify this in the question :) – Joanna Jan 03 '20 at 23:01
  • @AnatoliyR that makes a lot of sense thank you! – Joanna Jan 03 '20 at 23:03

1 Answers1

2

Array.toString() method, appends each of the array elements to a string builder using a for loop and returns the final string. So, if the size of the array is n, the new string will also be of size n.

So, it takes O(n) time to print the string representation of the array and O(n) space to create a new string of length n.

Time Complexity: O(n) Space Complexity: O(n)