String replacement in MATLAB - Time & Space Complexity
We want to understand how the time it takes to replace parts of a string changes as the string gets longer.
How does the work grow when we replace text inside a bigger string?
Analyze the time complexity of the following code snippet.
originalStr = "hello world hello";
searchStr = "hello";
replaceStr = "hi";
newStr = strrep(originalStr, searchStr, replaceStr);
This code replaces all occurrences of "hello" with "hi" in the given string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning the original string to find all matches of the search string.
- How many times: The scan goes through the entire string once, checking each position for a match.
As the string gets longer, the function checks more positions to find matches.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the string length.
Time Complexity: O(n*m)
This means the time to replace text grows linearly with the product of the string length and the search string length.
[X] Wrong: "Replacing text takes the same time no matter how long the string is."
[OK] Correct: The function must check each part of the string, so longer strings take more time.
Understanding how string operations grow with input size helps you explain your code choices clearly and confidently.
"What if we replaced multiple different substrings at once? How would the time complexity change?"