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
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
July 14, 2018
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 - What is the time complexity of this reverse string function? - Stack Overflow
No, divide and conquer has no complexity per se (or at least O(n)), it depend on what you make after dividing in parts... You can read divide and conquer or analysis of time complexity, read carefully the section about Master Theorem. What has complexity O(log(n)) is the binary search if the ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
๐ŸŒ
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.
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
๐ŸŒ
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.
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
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.
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ reverse a string in python
Reverse a string in Python
January 4, 2026 - The time complexity of reversing a string using these common methods is generally O(n), where n is always the length of the input string. This is because you need to process each character in the string at least once to create the reversed version.
๐ŸŒ
Scaler
scaler.com โ€บ topics โ€บ reverse-string-in-python
String reverse in Python
April 7, 2022 - Scaler Topics offers free certificate courses for all programming languages like Java, Python, C, C++, DSA etc. Learn from top MAANG experts and level up your skills. Explore now
๐ŸŒ
Quora
quora.com โ€บ What-will-be-runtime-complexity-for-Reverse-words-in-a-given-string
What will be runtime complexity for 'Reverse words in a given string'? - Quora
Answer: From the question details, youโ€™re actually asking about a particular algorithm. The algorithm youโ€™re using is to first reverse the whole string, then reverse the letters in each word. You seem to understand it takes O(n) time to reverse ...
๐ŸŒ
AlgoCademy
algocademy.com โ€บ link
Reverse String III in Python with O(n) Time Complexity
Iterate through the string from the end to the beginning and append each character to a new string. This approach is straightforward but not optimal because it involves creating a new string in each iteration, leading to O(n^2) time complexity.
๐ŸŒ
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
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.
๐ŸŒ
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.
๐ŸŒ
GitHub
gist.github.com โ€บ 98309363925a1b33d5f5
Reverse a list in python ยท GitHub
April 10, 2015 - Reverse a list in python. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
AlgoCademy
algocademy.com โ€บ link
Reverse String in Python | AlgoCademy
Given a string, write a function that reverses that string without using built-in functions or libraries. ... Your algorithm should run in O(n^2) time and use O(n) extra space.