0
0
PHPprogramming~5 mins

Trim functions in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Trim functions
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

As the string gets longer, the trim functions check characters from the ends until they find a non-space.

Input Size (n)Approx. Operations
10Up to 10 checks
100Up to 100 checks
1000Up to 1000 checks

Pattern observation: The number of checks grows roughly in direct proportion to the length of the string.

Final Time Complexity

Time Complexity: O(n)

This means the time to trim grows linearly with the string length.

Common Mistake

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

Interview Connect

Understanding how simple string operations scale helps you reason about performance in real projects and interviews.

Self-Check

"What if the string had no spaces at the ends? How would the time complexity change?"