0
0
Goprogramming~5 mins

Labelled break and continue in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Labelled break and continue
O(n²)
Understanding Time Complexity

When using labelled break and continue in Go, it is important to understand how these statements affect the flow of loops and the total steps the program takes.

We want to see how the number of operations changes as the input size grows when these labels control loop exits or skips.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


outer:
for i := 0; i < n; i++ {
    for j := 0; j < n; j++ {
        if j == i {
            continue outer
        }
        // some constant time work
    }
}
    

This code uses a labelled continue to jump to the next iteration of the outer loop when a condition is met inside the inner loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Nested loops with an inner loop that may break early using labelled continue.
  • How many times: Outer loop runs n times; inner loop runs fewer than n times each outer iteration because of the labelled continue.
How Execution Grows With Input

Because the inner loop stops early when j equals i, the total work is less than n x n.

Input Size (n)Approx. Operations
10About 45 inner loop steps
100About 4950 inner loop steps
1000About 499,500 inner loop steps

Pattern observation: The total steps grow roughly like the sum of numbers from 1 to n, which grows faster than n but slower than n squared.

Final Time Complexity

Time Complexity: O(n²)

This means the total steps grow roughly proportional to the square of the input size, even with the labelled continue.

Common Mistake

[X] Wrong: "Labelled continue makes the loops run in linear time because it skips inner iterations."

[OK] Correct: The inner loop still runs many times overall; skipping some iterations early does not reduce the total work enough to change the overall growth from quadratic.

Interview Connect

Understanding how labelled break and continue affect loop execution helps you reason about code efficiency and control flow clearly, a skill valuable in many programming tasks.

Self-Check

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