Labelled break and continue in Go - Time & Space 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.
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 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.
Because the inner loop stops early when j equals i, the total work is less than n x n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 45 inner loop steps |
| 100 | About 4950 inner loop steps |
| 1000 | About 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.
Time Complexity: O(n²)
This means the total steps grow roughly proportional to the square of the input size, even with the labelled continue.
[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.
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.
What if we replaced the labelled continue with a labelled break? How would the time complexity change?