0
0
Swiftprogramming~5 mins

If and if-else statements in Swift - Time & Space Complexity

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

We want to see how the time it takes to run code with if and if-else statements changes as the input changes.

Specifically, does a larger input value make the program take longer when using these statements?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func checkNumber(_ num: Int) {
    if num > 0 {
        print("Positive")
    } else if num < 0 {
        print("Negative")
    } else {
        print("Zero")
    }
}
    

This code checks if a number is positive, negative, or zero and prints a message accordingly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single if-else check on one number.
  • How many times: The checks happen once per function call.
How Execution Grows With Input

Each time you call the function with a number, it does a few quick checks only once.

Example InputApprox. Operations
101 check
1001 check
10001 check

Pattern observation: The number of operations remains constant (1 check) regardless of the input value.

Final Time Complexity

Time Complexity: O(1)

This means each if or if-else check takes the same small amount of time no matter what the input number is.

Common Mistake

[X] Wrong: "If statements take longer when the number is bigger because it has to check more conditions."

[OK] Correct: The if-else checks only a fixed number of conditions, so the size or value of the number does not make it slower.

Interview Connect

Understanding that simple if and if-else statements run quickly and do not slow down with bigger inputs helps you explain how your code handles decisions efficiently.

Self-Check

"What if we added a loop inside the if statement that runs n times? How would the time complexity change?"