0
0
Kotlinprogramming~5 mins

Kotlin REPL and script mode - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Kotlin REPL and script mode
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run Kotlin code changes when using REPL or script mode.

How does the way we run code affect how long it takes as the code grows?

Scenario Under Consideration

Analyze the time complexity of the following Kotlin script that sums numbers.


fun main() {
    val n = 10 // Assume n is a positive integer input
    var sum = 0
    for (i in 1..n) {
        sum += i
    }
    println(sum)
}

This script adds numbers from 1 to n and prints the total.

Identify Repeating Operations

Look for loops or repeated steps.

  • Primary operation: The for-loop adding each number to sum.
  • How many times: The loop runs n times, once for each number.
How Execution Grows With Input

As n gets bigger, the loop runs more times.

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

Pattern observation: The number of steps grows directly with n.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the script grows in a straight line as the input size increases.

Common Mistake

[X] Wrong: "Running code in REPL or script mode makes it run instantly no matter the input size."

[OK] Correct: REPL and script mode run code line by line, but the time still depends on how many steps the code has, like loops running many times.

Interview Connect

Understanding how code runs in different modes helps you explain performance clearly and shows you know how input size affects running time.

Self-Check

"What if we replaced the for-loop with a built-in sum function? How would the time complexity change?"