4

I was wondering what the Big-O of this code snippet is

def clear_list(my_list):
    while len(my_list) > 0:
        my_list.pop(0)
    return my_list

Would it be O(n^2) or O(n) because the while loop is O(n) or O(1) and pop(0) is O(n) as well. I don't think the while loop is O(log n) since no value that is being compared in the while loop is cut in half.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Jacklin213
  • 193
  • 2
  • 9

3 Answers3

4

It is O(N^2):

  • The while loop takes N steps, until all elements have been removed.

  • list.pop(0) is O(N); all elements in the list following have to shift up one step. That the list is shortened each step still gives you an average of 1/2 N steps over the whole process, where the 1/2 can be ignored (it doesn't matter when viewed asymptotically).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

It's going to be O(n^2) because in the while loop you have to go through all n elements, and in the pop you have to shift all of the elements that follow the first element.

Here's a link to a related answer: What is the time complexity of popping elements from list in Python?

Community
  • 1
  • 1
spirographer
  • 630
  • 4
  • 18
3

I just benchmarked this for you (EDIT: I assumed the return was misplaced since otherwise why do I even)

from time import time
def check(size):
    a = range(size)
    start = time()
    clear_list(a)
    return time() - start
check(40000) # About .4 seconds on my computer
check(80000) # About 1.6 seconds on my computer

Clearly O(n2)

displayName
  • 13,888
  • 8
  • 60
  • 75
Alec
  • 583
  • 3
  • 21