If-else expression assignment in Kotlin - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: A single if-else check.
- How many times: Exactly once per run.
The program does the same steps no matter what number you use.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of steps stays the same even if the input changes.
Time Complexity: O(1)
This means the program takes the same amount of time no matter the input size.
[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.
Understanding simple if-else assignments helps you explain how decisions in code affect speed, a key skill in many coding tasks.
"What if we replaced the if-else with a loop that checks every number up to 'number'? How would the time complexity change?"