If–else statement in Go - Time & Space Complexity
We want to see how the time taken by an if-else statement changes as the input changes.
Does the program take longer if the input is bigger?
Analyze the time complexity of the following code snippet.
func checkNumber(n int) string {
if n > 0 {
return "Positive"
} else {
return "Non-positive"
}
}
This code checks if a number is positive or not and returns a message.
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-else statement runs once no matter what the input number is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The time stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to run the if-else does not grow with input size; it stays constant.
[X] Wrong: "If-else takes longer when the number is bigger because it has to check more."
[OK] Correct: The if-else only checks once and does not loop or repeat, so input size does not affect it.
Understanding that simple decisions like if-else run in constant time helps you explain how your code behaves clearly and confidently.
"What if we added a loop inside the if-else that runs n times? How would the time complexity change?"