I'm struggling to understand Big O complexity. Is it correct that o_one() is "better" than o_n()?
def o_one(n: int):
# O(1) ?
print(n+1)
o_one(1)
o_one(2)
o_one(3)
def o_n(lst: list):
# O(n) ?
while lst:
print(lst.pop()+1)
o_n([3, 2, 1])
If I'm correct about the time complexities, then I must be misunderstanding something fundamental. Surely they are both equally efficient? First function needs to repeat 3 times to do the same thing?
edit: I'll provide another example then, since this one was problematic.
If I take my Linked List append method, which is O(1)...
def add_beginning(self, new):
# O(1)
new_node = Node(new)
new_node.next = self.head
self.head = new_node
... and add the ability for it to take a list of elements and append from that:
def add_beginning(self, new):
# O(n)
if type(new) != list:
new = [new]
while new:
new_node = Node(new.pop())
new_node.next = self.head
self.head = new_node
Did I make my function worse? I did change the time complexity from O(1) to O(n)