If statement in Go - Time & Space Complexity
We want to see how the time to run an if statement changes as the input changes.
Does the if statement take more time when inputs grow?
Analyze the time complexity of the following code snippet.
func checkNumber(n int) string {
if n > 0 {
return "Positive"
} else if n == 0 {
return "Zero"
} else {
return "Negative"
}
}
This code checks if a number is positive, zero, or negative and returns a string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single if-else check.
- How many times: Exactly once per function call.
The if statement runs once no matter what the input number is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same even if the input number changes.
Time Complexity: O(1)
This means the if statement takes the same amount of time no matter the input size.
[X] Wrong: "If statements take longer when the number is bigger."
[OK] Correct: The if statement only checks conditions once, so size or value does not affect time.
Understanding that simple decisions like if statements run in constant time helps you explain code efficiency clearly and confidently.
"What if we added a loop around the if statement? How would the time complexity change?"