0
0
Kotlinprogramming~5 mins

Launch coroutine builder in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Launch coroutine builder
O(n)
Understanding Time Complexity

When we use the launch coroutine builder in Kotlin, it starts a new task that runs alongside other code.

We want to understand how the time it takes to start and run these tasks changes as we start more of them.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import kotlinx.coroutines.*

fun main() = runBlocking {
    repeat(5) { i ->
        launch {
            println("Task $i running")
            delay(100L)
        }
    }
}

This code starts 5 coroutines that each print a message and wait briefly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The repeat(5) loop that launches 5 coroutines.
  • How many times: Exactly 5 times, once per coroutine started.
How Execution Grows With Input

As the number of coroutines started increases, the total number of launch operations grows directly with it.

Input Size (n)Approx. Operations
1010 launches
100100 launches
10001000 launches

Pattern observation: The work grows in a straight line as you add more coroutines.

Final Time Complexity

Time Complexity: O(n)

This means the time to start all coroutines grows directly with the number of coroutines you launch.

Common Mistake

[X] Wrong: "Starting many coroutines happens instantly and does not add up."

[OK] Correct: Each coroutine launch takes some time, so starting more coroutines adds more work overall.

Interview Connect

Understanding how launching many coroutines affects performance helps you write responsive and efficient Kotlin programs.

Self-Check

"What if we replaced launch with async? How would the time complexity change?"