Getting a slice is O(i_2 - i_1). This is because Python's internal representation of a list is an array, so you can start at i_1 and iterate to i_2.
For more information, see the Python Time Complexity wiki entry
You can also look at the implementation in the CPython source if you want to.
Answer from Sam Mussmann on Stack OverflowI think it's O(1) but some sources online say O(n)
Getting a slice is O(i_2 - i_1). This is because Python's internal representation of a list is an array, so you can start at i_1 and iterate to i_2.
For more information, see the Python Time Complexity wiki entry
You can also look at the implementation in the CPython source if you want to.
according to http://wiki.python.org/moin/TimeComplexity
it is O(k) where k is the slice size
What is meant by the assumption that "list-slicing takes constant-time"?
O(n+k) is the average case, which includes having to grow or shrink the list to adjust for the number of elements inserted to replace the original slice.
Your case, where you replace the slice with an equal number of new elements, the implementation only takes O(k) steps. But given all possible combinations of number of elements inserted and deleted, the average case has to move the n remaining elements in the list up or down.
See the list_ass_slice function for the exact implementation.
You're right, if you want to know the exact details it's best to use the source. The CPython implementation of setting a slice is in listobject.c.
If I read it correctly, it will...
- Count how many new elements you're inserting (or deleting!)
- Shift the n existing elements of the list over enough places to make room for the new elements, taking O(n) time in the worst case (when every element of the list has to be shifted).
- Copy over the new elements into the space that was just created, taking O(k) time.
That adds up to O(n+k).
Of course, your case is probably not that worst case: you're changing the last k elements of the list, so there might be no need for shifting at all, reducing the complexity to O(k) you expected. However, that is not true in general.
LeetCode 344
Consider the Python code attached that reverses a string recursively.
My thinking is that the list-slicing takes O(n-1) for both time and space in each of the O(n) recursive calls. Hence, both time and space complexities are O(n2) (the quadratic space complexity dominates the linear recursive space needed).
Is this correct?