If as an expression returning value in Kotlin - Time & Space Complexity
Let's see how using an if-expression that returns a value affects the time it takes to run code.
We want to know how the work grows when the input changes.
Analyze the time complexity of the following code snippet.
fun maxOfTwo(a: Int, b: Int): Int {
val max = if (a > b) a else b
return max
}
This code picks the bigger of two numbers using if as an expression that returns a value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single comparison between two numbers.
- How many times: Exactly once per function call.
Since the function compares only two numbers, the work stays the same no matter what.
| Input Size (n) | Approx. Operations |
|---|---|
| 2 | 1 comparison |
| 10 | 1 comparison |
| 1000 | 1 comparison |
Pattern observation: The number of operations does not grow with input size.
Time Complexity: O(1)
This means the time to run the code stays the same no matter the input size.
[X] Wrong: "Using if as an expression makes the code slower because it returns a value."
[OK] Correct: The if-expression just chooses between two values once, so it does not add extra work compared to a normal if statement.
Understanding how simple expressions like if returning a value affect time helps you explain your code clearly and confidently in interviews.
"What if we used if-expression inside a loop that runs n times? How would the time complexity change?"