Break and continue behavior in Kotlin - Time & Space 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.
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 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; forprintOdds, loop runs through all elements but skips printing evens.
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 findFirstEven | Approx. Operations in printOdds |
|---|---|---|
| 10 | Between 1 and 10 checks | 10 checks and some prints |
| 100 | Between 1 and 100 checks | 100 checks and some prints |
| 1000 | Between 1 and 1000 checks | 1000 checks and some prints |
Pattern observation: break can reduce work if condition met early; continue skips some steps but loop still runs fully.
Time Complexity: O(n)
This means the program's work grows roughly in direct proportion to the input size, even with break or continue.
[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.
Understanding how break and continue affect loop time helps you explain your code clearly and reason about efficiency in real tasks.
What if we replaced break with a flag variable to stop processing after finding the first even number? How would the time complexity change?