String interpolation in Swift - Time & Space Complexity
We want to understand how the time it takes to create a string using interpolation changes as the input grows.
How does the work increase when we add more parts to the string?
Analyze the time complexity of the following code snippet.
let name = "Alice"
let age = 30
let greeting = "Hello, \(name)! You are \(age) years old."
print(greeting)
This code creates a greeting message by inserting variables into a string using interpolation.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Copying characters and inserting variable values into the string.
- How many times: Once for each character and variable inserted.
As the length of the variables or the number of interpolations grows, the work to build the string grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps to copy and insert |
| 100 | About 100 steps to copy and insert |
| 1000 | About 1000 steps to copy and insert |
Pattern observation: The work grows roughly in direct proportion to the total length of the final string.
Time Complexity: O(n)
This means the time to create the string grows linearly with the size of the string being built.
[X] Wrong: "String interpolation is instant and does not depend on input size."
[OK] Correct: Actually, the program must copy and combine all parts, so bigger strings take more time.
Understanding how string building grows with input size helps you explain performance in real apps, showing you know how simple operations add up.
"What if we used a loop to build a string by adding many interpolated parts? How would the time complexity change?"