0
0
Rubyprogramming~5 mins

String interpolation with #{} in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String interpolation with #{}
O(n^2)
Understanding Time Complexity

We want to understand how the time it takes to create a string with embedded values changes as the input grows.

How does the work increase when we add more parts inside the string?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

names = ["Alice", "Bob", "Charlie", "Diana"]
result = ""
names.each do |name|
  result += "Hello, #{name}! "
end
puts result

This code builds a greeting string by adding a message for each name in the list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping over each name and concatenating a string (with interpolation) to the growing result using +=.
  • Key detail: In Ruby, strings are mutable, but += creates a new string each time by copying the existing content plus the new part.
  • How many times: n times, but each copy grows: lengths ~k for k=1 to n.
How Execution Grows With Input

Each concatenation copies the accumulating string, so total work is sum of 1+2+...+n.

Input Size (n)Approx. Copy Operations
10About 55 (1+2+...+10)
100About 5,050
1000About 500,500

Pattern observation: The work increases quadratically with the number of names.

Final Time Complexity

Time Complexity: O(n2)

This means the time to build the string grows quadratically as the number of names increases due to repeated copying of the growing string.

Common Mistake

[X] Wrong: "Each string += operation is O(1) constant time."

[OK] Correct: Strings are mutable in Ruby, but += creates a new string by copying the entire existing content plus the addition, leading to quadratic total time.

Interview Connect

Understanding how string building grows with input helps you write efficient code (e.g., use arrays and join) and explain your choices clearly.

Self-Check

"What if we used an array to collect all greetings first, then joined them once at the end? How would the time complexity change?"