Labeled break and continue in Javascript - Time & Space Complexity
We want to see how using labeled break and continue affects how long a program takes to run.
Specifically, we ask: how does skipping or stopping loops early change the work done as input grows?
Analyze the time complexity of the following code snippet.
outerLoop: for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (j === i) continue outerLoop;
if (i + j > n) break outerLoop;
}
}
This code uses labeled break and continue to jump out of or skip parts of loops based on conditions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops over i and j from 0 to n.
- How many times: Up to n times for outer loop, and up to n times for inner loop, but breaks and continues can stop inner loop early.
As n grows, the loops try to run more times, but labeled break and continue can stop inner loops early.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Less than 100 due to early breaks |
| 100 | Less than 10,000 but more than 1,000 |
| 1000 | Less than 1,000,000 but more than 100,000 |
Pattern observation: The work grows roughly with the square of n, but early exits reduce some work.
Time Complexity: O(n²)
This means the time grows roughly like the square of the input size, even with labeled breaks and continues.
[X] Wrong: "Using labeled break or continue always makes the code run in constant time."
[OK] Correct: Even though these statements can skip some work, the loops still mostly run many times as input grows, so time still grows with input size.
Understanding how labeled break and continue affect loop execution helps you explain code efficiency clearly and confidently in interviews.
"What if we removed the labeled break and continue and used only regular break and continue inside the inner loop? How would the time complexity change?"