Main function as entry point in Kotlin - Time & Space Complexity
We want to understand how the time a Kotlin program takes changes as the input grows.
Specifically, we look at the main function, which starts the program.
Analyze the time complexity of the following code snippet.
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
for (number in numbers) {
println(number)
}
}
This code prints each number in a list when the program starts.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list.
- How many times: Once for each number in the list.
As the list gets bigger, the program prints more numbers, so it takes more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
Pattern observation: The time grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "The main function always runs in constant time because it just starts the program."
[OK] Correct: The main function can do work like loops, so its time depends on what it does, not just that it starts.
Understanding how the main function's work grows with input helps you explain program efficiency clearly and confidently.
"What if the main function called another function that itself loops over the list twice? How would the time complexity change?"