I am trying to wrap my head around time complexity when it comes to algorithm design using Python.
I've been tasked with writing a function that meets the following requirements:
- Must be linear O(n) time
- must return the nth smallest number from a list of random numbers
I have found the following example online:
def nsmallest(numbers, nth):
result = []
for i in range(nth):
result.append(min(numbers))
numbers.remove(min(numbers))
return result
As I understand it, Big-O is an approximation and only dominant part of the function is considered when analyzing it time complexity.
So my question is:
Does calling min() within the loop influence the time complexity or does the function remain O(n) because min() executes in O(n) time?
Also, would adding another loop (not nested) to further parse the resulting list for the specific number keep the algorithm in linear time even if it contains two or three more constant operations per loop?