简体   繁体   中英

toString time and space complexity

Given the following method:

public String toString()
{
    if (_head == null)
        return "";
    String S="";
    WordNode currentNode = _head;
    while (currentNode != null)
    {
       S+=currentNode.getWord()+" ";
       currentNode = currentNode.getNext();
    }   
    return S;

}

What are time and space complexities? In Java, String is immutable object. How can it affect complexity? Thanks.

Time complexity is O(n), where n is the number of nodes, because you iterate over each node once. Space complexity is actually O(n*m), where n is the number of nodes and m is the length of the largest string you will create (which is the last string which contains all the words). This is because you create n strings, and string creation in java has memory usage proportional to the number of characters in the string (which in your case is maximum m). If you want to see exactly how much memory string creation uses, see this link: http://www.javamex.com/tutorials/memory/string_memory_usage.shtml .

Btw, you do not really need the if check in the beginning of your function because if the head is null, your while loop will not undergo any iterations and you will return an empty string anyway. Taking out this conditional will improve your time performance by a constant factor (but the time complexity will of course be the same).

The time complexity is O(L*N) where N is the number of nodes and L is the lenght of the resulting string:

If all but the first node contains a string of length 1 and the first node contains a string L-2*(N-1)-1 . Then the strings stored in S have lengths in the iterations of the loop have lengths

L-2*(N-1)
L-2*(N-2)
L-2*(N-3)
...
L

the sum of those values is in O(L*N) . Since allocating the strings takes time proportional to the sting size, the algorithm has time complexity O(N*L) .

The space complexity is O(L) since the stings stored in S have lengths in O(L) and intermediate results from previous iterations can be reclaimed by the garbage collector as soon as S is overwritten.

You can improve this to space and time complexity O(L) by using a StringBuilder .

public String toString()
{
    if (_head == null)
        return "";
    StringBuilder S=new StringBuilder();
    WordNode currentNode = _head;
    while (currentNode != null)
    {
       S.append(currentNode.getWord()).append(" ");
       currentNode = currentNode.getNext();
    }   
    return S.toString();

}

Each loop which iterate over n items has time complexity O(n). When you nest loop in another loop

while(...) {
   while(...) {
    ...
   }
}

it became O(n^2) and so forth.

As you are using only one loop, your method time complexity is O(n).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM