0
0
PHPprogramming~5 mins

Break statement with levels in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Break statement with levels
O(1)
Understanding Time Complexity

Let's see how using a break statement with levels affects how long a PHP program runs.

We want to know how the number of steps changes as the input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for ($i = 0; $i < $n; $i++) {
    for ($j = 0; $j < $m; $j++) {
        if ($j == 2) {
            break 2; // exit both loops
        }
        // some constant time operation
    }
}
    

This code loops over two levels but breaks out of both loops early when $j reaches 2.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The inner loop runs but breaks early at $j == 2.
  • How many times: The outer loop runs only once ($i = 0), and the inner loop runs 3 times (j=0,1,2) before break 2 exits both loops.
How Execution Grows With Input

Because of the break 2, both loops exit after just a few operations, regardless of input size.

Input Size (n)Approx. Operations
10About 3 steps
100About 3 steps
1000About 3 steps

Pattern observation: The work is constant because the loops terminate early, independent of $n.

Final Time Complexity

Time Complexity: O(1)

This means the program's running time stays constant as $n increases, thanks to the multilevel break stopping both loops early.

Common Mistake

[X] Wrong: "Because there are two loops, the time must be O(n*m)."

[OK] Correct: The break 2 exits both loops after $j reaches 2 in the first outer iteration, so total work is constant, not O(n*m).

Interview Connect

Understanding how break with levels changes loop behavior helps you explain code efficiency clearly and confidently in interviews.

Self-Check

What if the break statement was removed? How would the time complexity change?