Without even trying to bench it (you can do it easily), reverse_1
would be dead slow because of many things:
- loop with index
- constantly adding character to string, creating a copy each time.
So, slow because of loop & indexes, O(n*n)
time complexity because of the string copies, O(n)
complexity because it uses extra memory to create temp strings (which are hopefully garbage collected in the loop).
On the other hand s[::-1]
:
- doesn't use a visible loop
- returns a string without the need to convert from/to list
- uses compiled code from python runtime
So you cannot beat it in terms of time & space complexity and speed.
If you want an alternative you can use:
''.join(reversed(s))
but that will be slower than s[::-1]
(it has to create a list so join
can build a string back). It's interesting when other transformations are required than reversing the string.
Note that unlike C or C++ languages (as far as the analogy goes for strings) it is not possible to reverse the string with O(1)
space complexity because of the immutability of strings: you need twice the memory because string operations cannot be done in-place (this can be done on list of characters, but the str
<=> list
conversions use memory)