def check_palin(word):
    for i in range(len(word)//2):
        if word[i] != word[-(i+1)]:
            return False
    return True

I guess this is a bit more efficient solution as it iterates over half of the string and returns False whenever the condition is violated. But still the complexity would be O(n)

Answer from ZdaR on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/algorithms โ€บ what is the time complexity of reversing a string?
r/algorithms on Reddit: What is the time complexity of reversing a string?
October 23, 2020 -

I'm getting ready for an interview and practicing time complexity and I'm ok at recognizing the complexity for the code I've written myself but have a harder time when I throw in methods from the java library.

For example, I read that the method concat was similar to += and that concat time complexity was O(n^2). So if I reverse a string with the code below does that mean my time complexity is O(n^2)? With a space complexity of O(n) since? Where n is the length of the string.

String str="hello"
String s="";
for(int i =str.length()-1; i>=0;i--){
s+=str.substring(i,i+1);
}

With this code is the space complexity O(n) and the time complexity O(n)? Where n is the length of the string.

String str="hello";
char[] cArr = str.toCharArray();
int i =0;
int j = cArr.length-1;
char temp;
while(i<j){
    temp =cArr[i];
    cArr[i]=cArr[j];
    cArr[j]=temp;
    i++;
    j--;
}
str=String.valueOf(cArr);
Top answer
1 of 5
17
It should be simply O(n) where n is the length of string. If you think of a string as an array, you simply swap characters between left and right ends until they cross over the mid-point โ€” which means O(n/2) and simplified to O(n).
2 of 5
8
I don't know the time complexity of internal java lib functions by heart- I'll leave it to someone else to comment on that. What I do want to offer is a technique to sanity check your understanding. Asymptotic time complexity is very much on the numerical / theoretical side of things, but the actual computation time will reflect this behavior once the input size grows large enough. What you can do is repeatedly time the function on various input sizes spanning many orders of magnitude until you reach some limit (probably where the computation starts taking multiple seconds). You can then graph input size vs computation time, and see if its constant, linear, quadratic, logarithmic, etc., by eye. If you want a more precise measurement, take the log of both the input sizes and the computation times (so its a log-log plot), and a best-fit line through your data points (using a linear regression), the slope is the exponent of your variable in your measured time complexity (so a slope of 2 corresponds to observed quadratic time behavior). This isn't perfect, there can easily be huge constants throwing off your measured time complexity, you'll likely drop any logarithmic factors, etc. Its more of a coarse sanity check- if you think the algorithm is O(N2 ) but you experiment and see a near-straight line, and the log-log plot has a slope of 1, then you can reason that its likely not quadratic, its behaving more as a linear-time algorithm, and you should recheck your calculations.
Discussions

performance - String reversal in Python - Code Review Stack Exchange
A pre-allocated, mutable C-string ... linear time to copy the contents of the second string into the tail of the first. \$\endgroup\$ ... \$\begingroup\$ @IsmaelMiguel: As mentioned in the text reverse_g is the function with the slicing, i.e. the one in the answer. Renamed it so it is the correct name now, though. \$\endgroup\$ ... In terms of pure complexity, the answer ... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
March 11, 2019
Time complexity of reversed() in Python 3 - Stack Overflow
What is the time complexity of reversed() in Python 3? I think the answer would be O(1) but I want to clarify whether it is right or wrong. More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Reverse string time and space complexity - Stack Overflow
I have written different python codes to reverse a given string. But, couldn't able to figure the which one among them is efficient. Can someone point out the differences between these algorithms u... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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 *= 2

This 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.com
๐ŸŒ r/learnpython
4
3
December 1, 2019
People also ask

Are the Python string reversal methods similar to the ways you can reverse a string in C?
Some concepts like using a loop to reverse a string are common in both Python and C, but Python provides more built-in functions and methods like slicing, which are not available in C.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ reverse a string in python
Reverse a string in Python
How does string slicing work in Python?
String slicing in Python involves specifying a start, stop, and step value (default is 1) as indices to retrieve elements from the string. For example, string'[::-1] will return gnirts.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ reverse a string in python
Reverse a string in Python
What are the ways to reverse a string in Python using inbuilt function?
Python provides several built-in methods for string reversal, such as the [::-1] slicing method. However, there is no direct function like reverse() for strings.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ reverse a string in python
Reverse a string in Python
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ string reverse in python
Reverse String in Python - Scaler Topics
April 8, 2022 - We can reverse a string by iterating ... In this process, the new reversed string is created and printed. This method is generally slow because of the loop, as well as the copy we create each time we add a character to the string. The Time Complexity of this approach i...
๐ŸŒ
Better Programming
betterprogramming.pub โ€บ benchmarking-the-best-way-to-reverse-a-string-in-python-9c73d87b1b1a
Benchmarking the Best Way to Reverse a String in Python | by Nick Gibbon | Better Programming
September 16, 2019 - The complexity of the appending operation depends on the underlying implementation in the interpreter. Because Python strings are immutable, it is likely that each reversed_output = reversed_output + s[i] takes the current state of the output string and the new character and copies them to a new variable.
๐ŸŒ
Plain English
python.plainenglish.io โ€บ 4-ways-to-reverse-a-string-in-python-and-their-complexities-f6963e442152
4 Ways to Reverse a String in Python and Their Complexities | by Lulu Cao | Python in Plain English
March 28, 2024 - We did have some simplifications when analyzing the time and/or space complexities of solutions 2 and 3. But solution 4 has a direct time and space complexities of O(n) as it traverses through each character in the string directly and reverses them. And string[::-1] is even simpler than slice(None, None, -1). So, using the slicing syntax is the most recommended method to reverse a string in Python.
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ reverse a string in python
Reverse a string in Python
October 16, 2024 - When using a loop to reverse a string, the time complexity is O(n). The loop iterates through each character once, and the string concatenation operation (reversed_string += char) takes O(1) time for each iteration.
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ python-reverse-string
Reverse String In Python - Flexiple
March 18, 2024 - Time Complexity: O(n), where n is the length of the string. This is because we iterate through each character of the string once. Space Complexity: O(n), as we use additional space for the stack to store the characters of the string.
Find elsewhere
Top answer
1 of 2
52

Yes, this can be faster. Adding strings using + is usually a bad idea in Python, since strings are immutable. This means that whenever you add two strings, a new string needs to be allocated with the size of the resulting strings and then both string contents need to be copied there. Even worse is doing so in a loop, because this has to happen ever time. Instead you usually want to build a list of strings and ''.join them at the end (where you pay this cost only once).

But here you can just use the fact that strings can be sliced and you can specify a negative step:

def reverse_g(s):
    return s[::-1]

Here is a timing comparison for random strings of length from one up to 1M characters, where reverse is your function and reverse_g is this one using slicing. Note the double-log scale, for the largest string your function is almost a hundred thousand times slower.


The reverse_s function uses the reversed built-in, as suggested in the (now deleted, so 10k+ reputation) answer by @sleblanc and assumes you actually need the reversed string and not just an iterator over it:

def reverse_s(s):
    return ''.join(reversed(s))

The reverse_b function uses the C implementation, compiled with -O3, provided in the answer by @Broman, with a wrapper to create the string buffers and extract the output:

from ctypes import *

revlib = cdll.LoadLibrary("rev.so")
_reverse_b = revlib.reverse
_reverse_b.argtypes = [c_char_p, c_char_p, c_size_t]

def reverse_b(s):
    stri = create_string_buffer(s.encode('utf-8'))
    stro = create_string_buffer(b'\000' * (len(s)+1))
    _reverse_b(stro, stri, len(s) - 1)
    return stro.value.decode()

In the no interface version, just the call to _reverse_b is timed.

2 of 2
14

In terms of pure complexity, the answer is simple: No, it is not possible to reverse a string faster than O(n). That is the theoretical limit when you look at the pure algorithm.

However, your code does not achieve that because the operations in the loop are not O(1). For instance, output += stri[-1] does not do what you think it does. Python is a very high level language that does a lot of strange things under the hood compared to languages such as C. Strings are immutable in Python, which means that each time this line is executed, a completely new string is created.

If you really need the speed, you could consider writing a C function and call it from Python. Here is an example:

rev.c:

#include <stddef.h>
void reverse(char * stro, char * stri, size_t length) {
    for(size_t i=0; i<length; i++) stro[i]=stri[length-1-i];
    stro[length]='\0';
}

Compile the above function with this command:

gcc -o rev.so -shared -fPIC rev.c

And here is a python script using that function.

rev.py:

from ctypes import *

revlib = cdll.LoadLibrary("rev.so");
reverse = revlib.reverse
reverse.argtypes = [c_char_p, c_char_p, c_size_t]

hello = "HelloWorld"
stri = create_string_buffer(hello)
stro = create_string_buffer(b'\000' * (len(hello)+1))

reverse(stro, stri, len(stri)-1)

print(repr(stri.value))
print(repr(stro.value))

Please note that I'm by no means an expert on this. I tested this with string of length 10โธ, and I tried the method from Graipher, calling the C function from Python and calling the C function from C. I used -O3 optimization. When I did not use any optimization it was slower to call the C function from Python. Also note that I did NOT include the time it took to create the buffers.

stri[::-1] :                  0.98s
calling reverse from python : 0.59s
calling reverse from c:       0.06s

It's not a huge improvement, but it is an improvement. But the pure C program was WAY faster. The main function I used was this one:

int __attribute__((optimize("0"))) // Disable optimization for main
main(int argc, char ** argv) {     // so that reverse is not inlined

    const size_t size = 1e9;
    char * str = malloc(size+1);

    static const char alphanum[] =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    // Take data from outside the program to fool the optimizer        
    alphanum[atoi(argv[1])]='7';

    // Load string with random data to fool the optimizer        
    srand(time(NULL));
    for (size_t i = 0; i < size; ++i) {
        str[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
    }

    char *o = malloc(size+1);
    reverse(o, str, strlen(str));

    // Do something with the data to fool the optimizer        
    for(size_t i=0; i<size; i++) 
        if(str[i] != o[size-i-1]) {
            printf("Error\n");
            exit(1);
        }
}

Then, to get the runtime I ran:

gcc -O3 -pg rev.c; ./a.out; gprof a.out gmon.out | head -n8
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-reversed-vs-1-which-one-is-faster
Python - reversed() VS [::-1] , Which one is faster? - GeeksforGeeks
June 19, 2024 - Both slicing (A[::-1]) and the reversed() method provide a time complexity of O(n), where n is the length of the string.
๐ŸŒ
AlgoCademy
algocademy.com โ€บ link
Reverse String in Python | AlgoCademy
Optimized Solution: O(n) time complexity, O(n) space complexity. ... Empty string: The output should be an empty string. Single character string: The output should be the same as the input. String with spaces: The spaces should be reversed along with the characters.
๐ŸŒ
InterviewBit
interviewbit.com โ€บ coding problems โ€บ reverse string (c++, java, and python)
Reverse String (C++, Java, and Python) - InterviewBit
June 23, 2023 - def reverseString(self, s): left, right = 0, len(s) - 1 while left < right: s[left], s[right] = s[right], s[left] left, right = left + 1, right - 1 ยท Time Complexity:O(N), where N is the length of the string.
๐ŸŒ
Quora
quora.com โ€บ How-can-you-reverse-a-string-in-a-way-to-get-a-time-and-space-complexity-that-is-better-than-O-n
How to reverse a string in a way to get a time and space complexity that is better than O(n) - Quora
Answer (1 of 5): Of course not. A string is a sequence, and reversing the sequence always entails the entire sequence, thus \mathcal{O}(n). If the string is 100 characters long, it will take processing 100 chars to reverse it. If the string is 1000 characters long, it will take processing 1000 c...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ algorithm complexity with strings and slices
r/learnpython on Reddit: Algorithm complexity with strings and slices
December 1, 2019 -

Recently I was thinking about interview questions I got as an undergrad:
Things like "reverse a string" and "check if a string is a palindrome".

I did most of these in C++ with a loop and scrolling through the index using logic.

When I learned Python, I realized that I could "reverse a string" by simply going:

return mystring[::-1]

Likewise with "check if it is a palindrome" by doing:

return mystring == mystring[::-1]

The problem now is that, I don't know what kinda complexity it is.

From my point of view, it is constant, so O(1). But I am guessing that that is too good to be true as the string splicing is doing something behind the scenes.

Can anyone help me clarify?

Top answer
1 of 2
2

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 *= 2

This 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.

2 of 2
1

How difficult an algorithm is to write and how difficult it is to calculate are two separate things. Creating a reversed string with the shorthand still requires n order space and n order time. Keep in mind that, in most cases, creating a reversed array isn't necessary, you can just start at the top and go down, which is essentially what Python's reversed() function does

๐ŸŒ
Interviewing.io
interviewing.io โ€บ questions โ€บ reverse-string
How to Reverse a String [Interview Question + Solution]
September 13, 2018 - The time complexity is O(nยฒ) because each time we append a character to the end of the string, we end up creating a new string. This new string then gets assigned to the variable reversed_string.
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ reverse-words-in-a-string โ€บ solutions โ€บ 1488130 โ€บ python-reverse-mutable-string-in-place-o1-space-on-complexity-with-code-comments
Python reverse mutable string in place - O(1) space, O(N) ...
September 26, 2021 - Can you solve this real interview question? Reverse Words in a String - Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space.