Labeled break and continue in Java - Time & Space 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?
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 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.
Because the inner loop stops early each time, total steps grow roughly like n2/2.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 steps |
| 100 | About 5,050 steps |
| 1000 | About 500,500 steps |
Pattern observation: The total work grows quadratically with n.
Time Complexity: O(n^2)
This means the program's steps increase quadratically as input size grows.
[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).
Understanding how labeled break and continue affect loops shows you can read code carefully and explain its speed clearly.
"What if we replaced the labeled continue with a labeled break? How would the time complexity change?"