Constant values with const val in Kotlin - Time & Space Complexity
Let's see how using constant values affects the time it takes for a program to run.
We want to know how the program's work changes when it uses fixed values.
Analyze the time complexity of the following code snippet.
const val MAX_COUNT = 100
fun printMessage() {
for (i in 1..MAX_COUNT) {
println("Hello, Kotlin!")
}
}
This code prints a message a fixed number of times using a constant value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints the message.
- How many times: Exactly 100 times, because MAX_COUNT is a constant.
Since the loop runs a fixed 100 times, the work stays the same no matter what.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 (fixed) |
| 100 | 100 (fixed) |
| 1000 | 100 (fixed) |
Pattern observation: The number of operations does not grow with input size because the count is constant.
Time Complexity: O(1)
This means the program takes the same amount of time no matter how big the input is.
[X] Wrong: "Since there is a loop, the time must grow with input size."
[OK] Correct: Here, the loop count is fixed by a constant, so the time does not change with input size.
Understanding when code runs in constant time helps you explain efficiency clearly and confidently.
"What if MAX_COUNT was a variable input instead of a constant? How would the time complexity change?"