What is the time complexity and space complexity of array[::-1]

Viewed 5804

When reverse a list in Python, I usually use the array[::-1] for reversing and I know that a more common way might swap from two sides of the list. But I'm not sure the difference between these two solutions such as time complexity and space complexity.

Code for this two methods below:

def reverse(array):
    array[:] = array[::-1]


def reverse(array):
    start, end = 0, len(array)-1
    while start < end:
        array[start], array[end] = array[end], array[start]
        start += 1
        end -= 1
2 Answers

I ran an experiment using %%timeit on Jupyter with arrays of size 100, 1000 and 10000. The time taken by array[::-1] and reverse(array)(Swapping from two ends of the list) kept increasing almost linearly. However, the time taken by Python's inbuilt reversed function stayed almost constant, and so I guess that would be the best choice.

Time Comparison

Related