0
0
Kotlinprogramming~5 mins

Labeled break and continue in Kotlin - Time & Space Complexity

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

Scenario Under Consideration

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

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

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 10Up to 100 checks
100 x 100Up to 10,000 checks
1000 x 1000Up 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.

Final Time Complexity

Time Complexity: O(n * m)

This means the time grows roughly with the total number of elements in the matrix.

Common Mistake

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

Interview Connect

Understanding how labeled break and continue affect loop execution helps you explain control flow clearly and reason about performance in real code.

Self-Check

"What if we removed the labeled continue and used only break? How would the time complexity change?"