r/AskComputerScience • u/OkStress3344 • Jun 10 '26
Help with time complexity problem
Hey guys, so I'm a bit confused about what the correct worst-case time complexity for this function would be:
def func2(lst):
n = len(lst)
res = []
i = 1
while (i <= n):
res.insert(0, lst[i-1]])
i *= 2
return res
I originally said O(nlogn), assuming the insert would shift n items. However, after checking my answer with AI, as an answer key was not created, I realized that the total appends of insertion would be log(n), as it doesn't append every item in lst but rather logn items; therefore, the complexity is O((logn)^2). In class, however, my professor went over this question and said it would be O(nlogn) as the maximum or last insertion would shift n items. I tried explaining my O((logn)^2) reasoning, but I don't think I made a good case for it during class, and looking back, this answer still seems more correct to me, but I could definitely be wrong.
View all comments
Show parent comment
3
u/SignificantFidgets Jun 10 '26 edited Jun 10 '26
Ah... I missed that. For some reason I read that and thought the insertions were happening in the original list (which is weird, but still...).
In that case, you are correct (it's O(log^2 n)).
It's important that this is the standard Python list though, which has O(1) lookup time (i.e., time to get lst[i-1]).
Changing the problem to use a standard linked list, you'd need to walk the list to get the item. So the insertion on the smaller list would still be fast (O(1) with linked lists, in fact), but retrieving the value from the larger list would be Theta(n) for the last value retrieved. Add up all of those you'd get O(n) for the problem using a linked list.