Trim functions in PHP - Time & Space Complexity
We want to understand how the time to run trim functions changes as the input string gets longer.
How does the length of the string affect the work done by trim functions?
Analyze the time complexity of the following code snippet.
$string = " Hello World ";
$trimmed = trim($string);
$leftTrimmed = ltrim($string);
$rightTrimmed = rtrim($string);
// Using trim functions to remove spaces from the string ends
This code removes spaces from the start and/or end of a string using PHP's trim functions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning characters from the start and/or end of the string to find spaces.
- How many times: At most once per character from each end until a non-space is found.
As the string gets longer, the trim functions check characters from the ends until they find a non-space.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows roughly in direct proportion to the length of the string.
Time Complexity: O(n)
This means the time to trim grows linearly with the string length.
[X] Wrong: "Trim functions always run in constant time no matter the string size."
[OK] Correct: The functions must check characters from the ends until they find a non-space, so longer strings can take more time.
Understanding how simple string operations scale helps you reason about performance in real projects and interviews.
"What if the string had no spaces at the ends? How would the time complexity change?"