String concatenation in MATLAB - Time & Space Complexity
When we join strings together in MATLAB, the time it takes can change depending on how many strings we combine.
We want to understand how the work grows as we add more strings.
Analyze the time complexity of the following code snippet.
result = "";
for i = 1:n
result = [result, 'a'];
end
This code adds the letter 'a' to a string repeatedly, n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Concatenating the current string with a new character inside the loop.
- How many times: The loop runs n times, and each time concatenation happens.
Each time we add a character, MATLAB creates a new string by copying the old one and adding the new character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 (1+2+...+10) |
| 100 | About 5050 |
| 1000 | About 500500 |
Pattern observation: The work grows roughly like the square of n because each new string is longer than before.
Time Complexity: O(n^2)
This means the time to join strings grows much faster than the number of strings; doubling n makes the work about four times bigger.
[X] Wrong: "Adding one character each time takes the same time no matter how long the string is."
[OK] Correct: Each time MATLAB copies the whole existing string to add a new character, so longer strings take more time to copy.
Understanding how string joining grows helps you write faster code and explain your choices clearly in real projects or interviews.
"What if we used a cell array to collect characters first and joined them once at the end? How would the time complexity change?"