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

String concatenation behavior in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String concatenation behavior
O(n²)
Understanding Time Complexity

When we join strings together in C#, the way we do it affects how long the program takes to run.

We want to know how the time to combine strings grows as we add more pieces.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


string result = "";
string[] words = new string[] {"a", "b", "c", "d", "e"};

foreach (string word in words)
{
    result += word;
}
    

This code joins all words in the array into one string by adding each word to the result one by one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding one string to another inside a loop.
  • How many times: Once for each word in the array.
How Execution Grows With Input

Each time we add a word, the program copies the whole current string and the new word to make a new string.

Input Size (n)Approx. Operations
10About 55 copies (1+2+...+10)
100About 5050 copies
1000About 500,500 copies

Pattern observation: The work grows much faster than the number of words because each addition copies a longer string.

Final Time Complexity

Time Complexity: O(n²)

This means the time to join strings grows roughly with the square of the number of strings.

Common Mistake

[X] Wrong: "Adding strings in a loop always takes time proportional to the number of strings (O(n))."

[OK] Correct: Each addition copies the whole current string, so the work adds up more than just once per string.

Interview Connect

Understanding how string joining works helps you write faster code and explain your choices clearly in real projects.

Self-Check

"What if we used a StringBuilder instead of += inside the loop? How would the time complexity change?"