0
0
Kotlinprogramming~5 mins

If-else expression assignment in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If-else expression assignment
O(1)
Understanding Time Complexity

Let's see how the time it takes to run code changes when we use an if-else expression to assign a value.

We want to know how the program's steps grow as input changes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


val number = 10
val result = if (number % 2 == 0) {
    "Even"
} else {
    "Odd"
}
println(result)
    

This code checks if a number is even or odd and assigns a string based on that.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single if-else check.
  • How many times: Exactly once per run.
How Execution Grows With Input

The program does the same steps no matter what number you use.

Input Size (n)Approx. Operations
101 check
1001 check
10001 check

Pattern observation: The number of steps stays the same even if the input changes.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter the input size.

Common Mistake

[X] Wrong: "If-else checks take longer as the number gets bigger."

[OK] Correct: The check only looks at the number once, so size doesn't affect time.

Interview Connect

Understanding simple if-else assignments helps you explain how decisions in code affect speed, a key skill in many coding tasks.

Self-Check

"What if we replaced the if-else with a loop that checks every number up to 'number'? How would the time complexity change?"