Skip to content
Advertisement

time complexity of concatenating strings in python

What is is the time complexity for the following function in Python?
The function takes two inputs, string1 and string2, concatenates them together using “+” and returns the concatenated string.

def concat_strings(string1, string2):
    return string1 + " " + string2

is it O(n + m) where n is the length of string1 and m is the length of string2?
thanks!

Advertisement

Answer

Yes, it is. Strings in Python are immutable, once-allocated data. So when you do string1 + string2, it will allocate a size n+m, then copy both strings.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement