String templates and interpolation in Kotlin - Time & Space Complexity
We want to understand how the time to create strings with templates grows as the input changes.
How does the work increase when we build strings using variables inside them?
Analyze the time complexity of the following code snippet.
fun greet(names: List): List {
val greetings = mutableListOf()
for (name in names) {
greetings.add("Hello, $name!")
}
return greetings
}
This code creates a greeting message for each name in a list using string templates.
- Primary operation: Looping through each name in the list.
- How many times: Once for every name in the input list.
As the number of names grows, the number of greetings created grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greetings created |
| 100 | 100 greetings created |
| 1000 | 1000 greetings created |
Pattern observation: The work grows directly with the number of names.
Time Complexity: O(n)
This means the time to create greetings grows in a straight line with the number of names.
[X] Wrong: "String templates make the code run slower exponentially because they are complex."
[OK] Correct: Each string template is processed once per item, so the time grows linearly, not exponentially.
Understanding how string building scales helps you write efficient code and explain your reasoning clearly.
"What if we used nested loops to create greetings for pairs of names? How would the time complexity change?"