0
0
PHPprogramming~5 mins

String concatenation operator in PHP - Time & Space Complexity

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

When we join strings together in PHP using the concatenation operator, it takes some time depending on the size of the strings.

We want to understand how the time to join strings grows as the strings get longer or as we join more strings.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$string = "";
for ($i = 0; $i < $n; $i++) {
    $string .= "a";
}
    

This code builds a string by adding the letter "a" one by one, repeating $n times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding one character to the string using concatenation inside a loop.
  • How many times: The concatenation happens once per loop, so $n times.
How Execution Grows With Input

Each time we add a character, PHP creates a new string by copying the old string and adding the new character.

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

Pattern observation: The total work grows roughly like the square of n because each concatenation copies the whole string built so far.

Final Time Complexity

Time Complexity: O(n²)

This means the time to build the string grows roughly with the square of the number of characters added.

Common Mistake

[X] Wrong: "Concatenating strings in a loop is always fast and takes time proportional to n."

[OK] Correct: Each concatenation copies the entire string so far, making the total time grow much faster than just n.

Interview Connect

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

Self-Check

"What if we used an array to collect characters and joined them once at the end? How would the time complexity change?"