Labeled break and continue in Kotlin - Time & Space Complexity
We want to understand how using labeled break and continue affects the time a program takes to run.
Specifically, we ask: How does the number of steps change as the input grows?
Analyze the time complexity of the following code snippet.
fun searchMatrix(matrix: Array, target: Int) {
outer@ for (row in matrix) {
for (value in row) {
if (value == target) break@outer
if (value > target) continue@outer
}
}
}
This code searches for a target number in a 2D matrix, using labeled break and continue to control loops.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops over rows and values in the matrix.
- How many times: Outer loop runs for each row, inner loop runs for each value in that row until break or continue.
As the matrix size grows, the loops run more times, but labeled break and continue can stop inner loops early.
| Input Size (n x m) | Approx. Operations |
|---|---|
| 10 x 10 | Up to 100 checks |
| 100 x 100 | Up to 10,000 checks |
| 1000 x 1000 | Up to 1,000,000 checks |
Pattern observation: The number of operations grows roughly with the total number of elements, but early breaks can reduce work.
Time Complexity: O(n * m)
This means the time grows roughly with the total number of elements in the matrix.
[X] Wrong: "Using labeled break or continue makes the loops run faster always."
[OK] Correct: Labeled break and continue only skip some steps but do not change the worst-case number of checks if the target is not found early.
Understanding how labeled break and continue affect loop execution helps you explain control flow clearly and reason about performance in real code.
"What if we removed the labeled continue and used only break? How would the time complexity change?"