0
0
Kotlinprogramming~5 mins

If as an expression returning value in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If as an expression returning value
O(1)
Understanding Time 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.

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single comparison between two numbers.
  • How many times: Exactly once per function call.
How Execution Grows With Input

Since the function compares only two numbers, the work stays the same no matter what.

Input Size (n)Approx. Operations
21 comparison
101 comparison
10001 comparison

Pattern observation: The number of operations does not grow with input size.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the code stays the same no matter the input size.

Common Mistake

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

Interview Connect

Understanding how simple expressions like if returning a value affect time helps you explain your code clearly and confidently in interviews.

Self-Check

"What if we used if-expression inside a loop that runs n times? How would the time complexity change?"