How Strings Work Differently Across Languages in DSA Python - Complexity Walkthrough
Strings are used everywhere in programming, but how they behave can change depending on the language.
We want to understand how these differences affect the time it takes to work with strings.
Analyze the time complexity of concatenating strings in Python.
result = ""
for s in list_of_strings:
result += s
This code joins many small strings into one big string by adding each one at the end.
Look at what repeats as the input grows.
- Primary operation: Adding a string to the end of another string.
- How many times: Once for each string in the list.
Each time we add a string, Python creates a new string by copying the old one and the new part.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 copies (1+2+...+10) |
| 100 | About 5050 copies |
| 1000 | About 500,500 copies |
Pattern observation: The work grows much faster than the number of strings because each addition copies all previous data again.
Time Complexity: O(n²)
This means the time to join strings grows roughly with the square of the number of strings, making it slow for large lists.
[X] Wrong: "Adding strings with += is always fast and linear in time."
[OK] Correct: Each += creates a new string by copying all existing characters, so the total work adds up quickly.
Understanding how string operations cost time helps you write efficient code and explain your choices clearly in interviews.
"What if we used a list to collect strings first and then joined them all at once? How would the time complexity change?"