What is the most efficient way to reverse a string in Python? - Stack Overflow
Fastest way to reverse a string - and it's not extended string splicing?
Algorithm complexity with strings and slices
The python page on time-complexity shows that slicing lists has a time-complexity of O(k), where "k" is the length of the slice. That's for lists, not strings, but the complexity can't be O(1) for strings since the slicing must handle more characters as the size is increased. At a guess, the complexity of slicing strings would also be O(k). We can write a little bit of code to test that guess:
import time
StartSize = 2097152
size = StartSize
for _ in range(10):
# create string of size "size"
s = '*' * size
# now time reverse slice
start = time.time()
r = s[::-1]
delta = time.time() - start
print(f'Size {size:9d}, time={delta:.3f}')
# double size of the string
size *= 2This uses a simple method of timing. Other tools exist, but this is simple. When run I get:
$ python3 test.py Size 2097152, time=0.006 Size 4194304, time=0.013 Size 8388608, time=0.024 Size 16777216, time=0.050 Size 33554432, time=0.098 Size 67108864, time=0.190 Size 134217728, time=0.401 Size 268435456, time=0.808 Size 536870912, time=1.610 Size 1073741824, time=3.192
which shows the time doubles when doubling the size of the string for each reverse slice. So O(n) (k == n for whole-string slicing).
Edit: spelling.
More on reddit.comWhat is the time complexity of reversing a string?
Videos
An interview question I got was the following:
Write a function that reversed a string s. Speed is important.
I gave them back a 1 liner, returning
s[::-1]
I was told there's a faster method with some optimisations possible.
Some assumptions:
-
Reasonable real world memory limitations.
-
Input string is a valid string.
-
No information on distribution or makeup of strings
How should I have done it?