0
0
PHPprogramming~5 mins

Continue statement with levels in PHP - Time & Space Complexity

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

Let's see how using the continue statement with levels affects how many times parts of the code run.

We want to know how skipping certain loops changes the total work done.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for ($i = 0; $i < $n; $i++) {
    for ($j = 0; $j < $n; $j++) {
        if ($j % 2 == 0) {
            continue 2; // skips to next $i iteration
        }
        // some constant time operation
    }
}
    

This code loops over two levels. When $j is even, it skips the rest of inner and outer loop body and moves to the next $i.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Nested loops over $i and $j.
  • How many times: Outer loop runs $n times; inner loop runs partially due to continue 2.
How Execution Grows With Input

Because continue 2 skips inner and outer loop when $j is even, inner loop does very little work per outer loop.

Input Size (n)Approx. Operations
105 (one inner iteration per outer loop when $j is odd)
10050
1000500

Pattern observation: Operations grow roughly linearly with input size, not squared.

Final Time Complexity

Time Complexity: O(n)

This means the total work grows in direct proportion to the input size.

Common Mistake

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

[OK] Correct: The continue 2 skips many inner loop steps, so the inner loop does not fully run each time.

Interview Connect

Understanding how control statements like continue with levels affect loops helps you explain code efficiency clearly and confidently.

Self-Check

"What if we changed continue 2 to continue 1? How would the time complexity change?"