Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of string slice? O(k) or O(n)

Is the time complexity of python str slice O(k) or O(n)?

The answers I am reading suggest its O(k) but I don't understand how.

For example

my_str = "thisismystringfortesting"

sub_str = my_str[3:10]

I understand its extracting only (k) characters, but doesn't the operation have to convert the whole string into a list first before the slice? My thought process is that the conversion of the entire string into a list alone would cost O(n). Unless only part of the string gets converted into a list?

So can someone please explain is string slicing on Python O(k) or O(n)?

Thanks so much!

like image 786
able-leopard Avatar asked Oct 20 '25 18:10

able-leopard


1 Answers

The relevant code is here and it is O(k) as it can be seen line 1628

result_buf = PyBytes_AS_STRING(result);
for (cur = start, i = 0; i < slicelength;cur += step, i++) {
        result_buf[i] = source_buf[cur];
}
return result;
like image 50
Jacques Gaudin Avatar answered Oct 22 '25 08:10

Jacques Gaudin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!