0
0
C Sharp (C#)programming~5 mins

String interpolation and formatting in C Sharp (C#) - Time & Space Complexity

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

Scenario Under Consideration

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

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

As the number of numbers grows, the work to build the string grows more than just once per number.

Input Size (n)Approx. Operations
10About 55 string operations
100About 5050 string operations
1000About 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.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

Understanding how string building scales helps you write efficient code and explain your choices clearly in real projects or interviews.

Self-Check

"What if we used a StringBuilder instead of adding strings directly? How would the time complexity change?"