0
0
Kotlinprogramming~5 mins

Constant values with const val in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Constant values with const val
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Since the loop runs a fixed 100 times, the work stays the same no matter what.

Input Size (n)Approx. Operations
10100 (fixed)
100100 (fixed)
1000100 (fixed)

Pattern observation: The number of operations does not grow with input size because the count is constant.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter how big the input is.

Common Mistake

[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.

Interview Connect

Understanding when code runs in constant time helps you explain efficiency clearly and confidently.

Self-Check

"What if MAX_COUNT was a variable input instead of a constant? How would the time complexity change?"