0

Using an ADT Linked List and the following code, how would I express the runtime in Big O Notation?:

def reverse (self):
 (1)if self._head is not None:
      (2)temp = self._head.item
      (3)self._head = self._head.next
      (4)self.reverse()
      (5)self.append(temp)

My thought process: Lines 1 - 3 were essentially constant as they are just setting and getting items from the beginning of the Linked List, and line 5 is theta(n) by definition. Each time the list becomes smaller, so I thought the function runs n(n-1)(n-2).... implying that it is theta(n!). Could I get some help?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Ryan Nemec
  • 1
  • 1
  • 2

1 Answers1

1

This is a recursive function therefore line 4 isn't theta(n) by definition.

This will actually run in O(n).

Basically this function's complexity is:

T(n) = T(n - 1) + O(1) // T(n - 1) for the recursive call on a list one element shorter, constant for other operations.

To solve this we use induction:

T(n) = n * O(1) + T(0) = n * O(1) + O(1) = O(n)

For the append, indeed in the worst case it might be O(n) but the amortized worst case scenario is O(1).

Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94