If and if-else statements in Swift - Time & Space 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?
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 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.
Each time you call the function with a number, it does a few quick checks only once.
| Example Input | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of operations remains constant (1 check) regardless of the input value.
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.
[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.
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.
"What if we added a loop inside the if statement that runs n times? How would the time complexity change?"