0

I'm familiar with running time for both of the following methods which is O(N). However, I'm not familiar with space complexity. Since these methods consists simply of assignment statements, comparison statements, and loops, I assume that the space complexity is just O(1), but want to make sure. Thank you.

//first method 
public static <E> Node<E> buildList(E[] items) {
    Node<E> head = null; 
    if (items!=null && items.length>0) {
        head = new Node<E> (items[0], null);
        Node<E> tail = head;
        for (int i=1; i<items.length; i++) {
            tail.next = new Node<E>(items[i], null);
            tail = tail.next;
        }
    }
    return head;
}

//second method
public static <E> int getLength(Node<E> head) {
    int length = 0; 
    Node<E> node = head;
    while (node!=null) {
        length++;
        node = node.next; 
    }
    return length;
}
Mr.Rabbit
  • 101
  • 8

1 Answers1

1

As described in this post, space complexity is related to the amount of memory used by the algorithm, depending on the size of the input.

For instance an algorithm with O(1) space complexity uses a fixed amount of memory, independently of the input size. This is the case of your second algorithm that basically only uses a few extra variables.

An algorithm with O(n) space complexity uses an amount of memory proportional to its input size. This is the case of your first algorithm that performs one allocation (one new) for each element of the input.

Community
  • 1
  • 1
serge-sans-paille
  • 2,011
  • 8
  • 9