0
0
MATLABdata~5 mins

String concatenation in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String concatenation
O(n^2)
Understanding Time 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.

Scenario Under Consideration

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

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

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
10About 55 (1+2+...+10)
100About 5050
1000About 500500

Pattern observation: The work grows roughly like the square of n because each new string is longer than before.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

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

Self-Check

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