Kotlin REPL and script mode - Time & Space 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?
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.
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.
As n gets bigger, the loop runs more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with n.
Time Complexity: O(n)
This means the time to run the script grows in a straight line as the input size increases.
[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.
Understanding how code runs in different modes helps you explain performance clearly and shows you know how input size affects running time.
"What if we replaced the for-loop with a built-in sum function? How would the time complexity change?"