0
0
Rubyprogramming~5 mins

String concatenation and << in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String concatenation and <<
O(n²)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time we add a string, the program copies the whole current result plus the new string.

Input Size (n)Approx. Operations
10About 55 copies (1+2+...+10)
100About 5050 copies
1000About 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.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

Knowing how string joining works helps you write faster code and explain your choices clearly in real projects and interviews.

Self-Check

"What if we used << instead of += to join strings? How would the time complexity change?"