0
0
Rustprogramming~5 mins

If–else expression in Rust - Time & Space Complexity

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

We want to see how the time it takes to run an if-else expression changes as the input changes.

Specifically, does choosing one path or the other affect how long the program runs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fn check_number(n: i32) -> &'static str {
    if n > 0 {
        "Positive"
    } else {
        "Non-positive"
    }
}
    

This code checks if a number is positive or not and returns a message accordingly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

The program does one simple check no matter what the input number is.

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

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

Final Time Complexity

Time Complexity: O(1)

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

Common Mistake

[X] Wrong: "If-else expressions take longer when the input number is bigger."

[OK] Correct: The if-else only checks one condition once, so the input size does not affect how long it takes.

Interview Connect

Understanding that simple decisions like if-else checks run in constant time helps you explain how your code behaves clearly and confidently.

Self-Check

"What if we added a loop inside the if or else block? How would the time complexity change?"