0
0
Javaprogramming~5 mins

Labeled break and continue in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Labeled break and continue
O(n^2)
Understanding Time Complexity

We want to see how using labeled break and continue affects how long a program runs.

Specifically, we ask: how does the program's steps grow as input gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


public class Example {
    public static void labeledLoop(int n) {
        outer: for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (j == i) continue outer;
            }
        }
    }
}
    

This code uses a labeled continue to jump out of the inner loop and continue the outer loop early.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Nested loops with an early jump using labeled continue.
  • How many times: Outer loop runs n times; for each i, inner loop body executes (i+1) times; total ~ n2/2.
How Execution Grows With Input

Because the inner loop stops early each time, total steps grow roughly like n2/2.

Input Size (n)Approx. Operations
10About 55 steps
100About 5,050 steps
1000About 500,500 steps

Pattern observation: The total work grows quadratically with n.

Final Time Complexity

Time Complexity: O(n^2)

This means the program's steps increase quadratically as input size grows.

Common Mistake

[X] Wrong: "Early exit from inner loop makes overall time O(n)."

[OK] Correct: The inner loop stops at j==i each time, but total operations is sum_{i=0}^{n-1} (i+1) ≈ n2/2, still O(n^2).

Interview Connect

Understanding how labeled break and continue affect loops shows you can read code carefully and explain its speed clearly.

Self-Check

"What if we replaced the labeled continue with a labeled break? How would the time complexity change?"