0
0
Kotlinprogramming~5 mins

Break and continue behavior in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Break and continue behavior
O(n)
Understanding Time Complexity

When we use break or continue in loops, it changes how many times the loop runs.

We want to see how these keywords affect the total work the program does as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun findFirstEven(numbers: List<Int>): Int? {
    for (num in numbers) {
        if (num % 2 == 0) {
            return num
        }
    }
    return null
}

fun printOdds(numbers: List<Int>) {
    for (num in numbers) {
        if (num % 2 == 0) continue
        println(num)
    }
}
    

This code searches for the first even number and stops early, and also prints only odd numbers skipping evens.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of numbers.
  • How many times: For findFirstEven, loop stops early when an even number is found; for printOdds, loop runs through all elements but skips printing evens.
How Execution Grows With Input

For findFirstEven, if the first even number is near the start, the loop runs few times; if none or last, it runs through all.

For printOdds, the loop always checks every number, but skips printing evens.

Input Size (n)Approx. Operations in findFirstEvenApprox. Operations in printOdds
10Between 1 and 10 checks10 checks and some prints
100Between 1 and 100 checks100 checks and some prints
1000Between 1 and 1000 checks1000 checks and some prints

Pattern observation: break can reduce work if condition met early; continue skips some steps but loop still runs fully.

Final Time Complexity

Time Complexity: O(n)

This means the program's work grows roughly in direct proportion to the input size, even with break or continue.

Common Mistake

[X] Wrong: "Using break always makes the loop run in constant time."

[OK] Correct: Sometimes the loop stops early, but if the condition is met late or never, the loop still runs through all items.

Interview Connect

Understanding how break and continue affect loop time helps you explain your code clearly and reason about efficiency in real tasks.

Self-Check

What if we replaced break with a flag variable to stop processing after finding the first even number? How would the time complexity change?