r/AskComputerScience • • 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.

1 Upvotes

11 comments sorted by

View all comments

Show parent comment

4

u/Objective_Mine MSCS, CS Pro (10+) Jun 10 '26

Yeah, the devil is in the details, which is one of the reasons why I'm not particularly fond of DSA being taught using Python or some other particular real-world programming language with its own implementation details.

Since it does look like Python, though, and there's no mention of linked lists, it would make sense that the source list would be a standard array-backed list with random access. It would be a bit of a gotcha if it weren't. (It's of course perfectly valid and valuable to ask what would happen to the complexity if the source or target data structures were something different, though.)

1

u/not-just-yeti Jun 10 '26 edited Jun 18 '26

And "worse", python's list-implementation isn't part of the language spec, so it could change in future versions (or even differ between two totally-compliant python implementations). In particular, I can imagine the standard implementation tuning arraylist to allow θ(1) prepending, or changing to treelists which can achieve ~ log_32 (n) operations including insert-in-the-middle and indexing. Or heck, an implementation might dynamically switch between implementations depending on how the list is being used (similar to how Java (OpenJDK)'s hash-tables switch between using linked-lists as buckets when short and using binary search trees if a bucket gets large).