In the mission Algorithms we are asked to find time complexities of the two following functions. I think that function 1 has a constant time complexity (find the length of the list) and function 2 has linear time complexity (we have to iterate over all elements in the list). But this answer appears to be wrong. Is it my mistake or is it a mistake of Dataquest?:
# Check whether a list is empty -- Implementation 1
def is_empty_1(ls):
if length(ls) == 0:
return True
else:
return False
is_empty_1_complexity = "constant"
# Check whether a list is empty -- Implementation 2
def is_empty_2(ls):
for element in ls:
return False
return True
is_empty_2_complexity = "linear"
Hi, Bruno. Thank you for your hint. I see that lists have different lengths. So the second function should have a linear time complexity as I said because you iterate over each element in the list. And the first one should have a linear or constant time complexity. It depends on the implementation of the function len(). But the answer from Dataquest says that the first function has linear and the second function has constant time complexities. I don’t understand why.
Thank you, Bruno. I was not very attentive. So because of the implementation of the function length() the first function has linear time complexity. And of course, the second one has a constant time complexity because of the statement return in the for loop.