0
0
Rustprogramming~5 mins

If expression in Rust - Time & Space Complexity

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

We want to see how using an if expression affects how long a program takes to run.

Specifically, does choosing between two paths change the work as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fn check_number(n: i32) -> i32 {
    if n > 0 {
        n * 2
    } else {
        n - 2
    }
}
    

This code checks if a number is positive and returns a value based on that check.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single if check (comparison) and one arithmetic operation.
  • How many times: Exactly once per function call, no loops or recursion.
How Execution Grows With Input

Each time we call the function, it does the same small amount of work, no matter the input size.

Input Size (n)Approx. Operations
101 if check + 1 arithmetic
1001 if check + 1 arithmetic
10001 if check + 1 arithmetic

Pattern observation: The work stays the same no matter how big the input number is.

Final Time Complexity

Time Complexity: O(1)

This means the time to run does not grow with input size; it stays constant.

Common Mistake

[X] Wrong: "If expressions take longer when the number is bigger because the computer has to compare bigger numbers."

[OK] Correct: Comparing numbers is a simple operation that takes the same time regardless of size in this context.

Interview Connect

Understanding that simple if checks do not slow down your program as inputs grow helps you focus on parts that really matter for performance.

Self-Check

"What if we added a loop inside the if expression? How would the time complexity change?"