0
0
Kotlinprogramming~5 mins

CancellationException behavior in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: CancellationException behavior
O(n)
Understanding Time Complexity

When working with Kotlin coroutines, it's important to understand how cancellation affects program flow.

We want to see how the CancellationException influences the running time of coroutine code.

Scenario Under Consideration

Analyze the time complexity of the following coroutine code snippet.


    suspend fun processItems(items: List<Int>) {
        for (item in items) {
            if (!kotlin.coroutines.coroutineContext.isActive) throw CancellationException()
            delay(10) // simulate work
            println(item)
        }
    }
    

This code processes a list of items, checking for cancellation before each step.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each item in the list.
  • How many times: Once for each item in the input list.
How Execution Grows With Input

Each item causes a check for cancellation and a small delay, so work grows with the list size.

Input Size (n)Approx. Operations
1010 cancellation checks + 10 delays
100100 cancellation checks + 100 delays
10001000 cancellation checks + 1000 delays

Pattern observation: The total work increases directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the number of items processed.

Common Mistake

[X] Wrong: "CancellationException makes the loop stop immediately, so time is constant."

[OK] Correct: Cancellation only stops the loop when detected; until then, all items are processed, so time depends on input size.

Interview Connect

Understanding how cancellation affects coroutine loops helps you reason about program responsiveness and efficiency in real apps.

Self-Check

"What if the cancellation check was removed? How would the time complexity change?"