String interpolation and formatting in C Sharp (C#) - Time & Space Complexity
We want to understand how the time it takes to create formatted strings changes as the input size grows.
How does the work needed to build a string grow when we add more data to format?
Analyze the time complexity of the following code snippet.
string FormatNumbers(int[] numbers)
{
string result = "";
foreach (int num in numbers)
{
result += $"Number: {num}, ";
}
return result;
}
This code builds a string by adding each number formatted with text, one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number and appending a formatted string.
- How many times: Once for every number in the input array.
As the number of numbers grows, the work to build the string grows more than just once per number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 string operations |
| 100 | About 5050 string operations |
| 1000 | About 500,500 string operations |
Pattern observation: The operations grow roughly like the square of the input size because each new string addition copies the whole existing string.
Time Complexity: O(n²)
This means the time to build the string grows much faster than the number of items, because each addition copies the whole string so far.
[X] Wrong: "Adding strings in a loop always takes time proportional to the number of items (O(n))."
[OK] Correct: Because strings are immutable, each addition creates a new string copying all previous content, causing the total work to grow much faster.
Understanding how string building scales helps you write efficient code and explain your choices clearly in real projects or interviews.
"What if we used a StringBuilder instead of adding strings directly? How would the time complexity change?"