0
0
Javascriptprogramming~5 mins

Labeled break and continue in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Labeled break and continue
O(n²)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
10Less than 100 due to early breaks
100Less than 10,000 but more than 1,000
1000Less 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.

Final Time Complexity

Time Complexity: O(n²)

This means the time grows roughly like the square of the input size, even with labeled breaks and continues.

Common Mistake

[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.

Interview Connect

Understanding how labeled break and continue affect loop execution helps you explain code efficiency clearly and confidently in interviews.

Self-Check

"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?"