String concatenation and << in Ruby - Time & Space Complexity
We want to understand how the time it takes to join strings grows as we add more pieces.
How does using different ways to combine strings affect the work done?
Analyze the time complexity of the following code snippet.
result = ""
strings = ["a", "b", "c", "d", "e"]
strings.each do |str|
result += str
end
puts result
This code joins many small strings into one big string using the + operator inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding strings together with
+=inside a loop. - How many times: Once for each string in the array.
Each time we add a string, the program copies the whole current result plus the new string.
| 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; it grows roughly like the square of the input size.
Time Complexity: O(n²)
This means the time to join strings grows much faster as you add more strings, because each addition copies all the previous data.
[X] Wrong: "Adding strings with += inside a loop is always fast and grows linearly."
[OK] Correct: Each += creates a new string by copying the old one, so the work adds up more than just once per string.
Knowing how string joining works helps you write faster code and explain your choices clearly in real projects and interviews.
"What if we used << instead of += to join strings? How would the time complexity change?"